changing the xlim by date in matplotlib

  • Last Update :
  • Techknowledgy :

If I do something like this on matplotlib v1.3.1:

import datetime
import matplotlib.pyplot as plt

x = [datetime.date(2014, 1, 29)] * 3
y = [2, 4, 1]

fig, ax = plt.subplots()
ax.plot_date(x, y, markerfacecolor = 'CornflowerBlue', markeredgecolor = 'white')
fig.autofmt_xdate()
ax.set_xlim([datetime.date(2014, 1, 26), datetime.date(2014, 2, 1)])
ax.set_ylim([0, 5])

Here is a more general solution for other beginners.

import matplotlib.pyplot as plt
import datetime as dt

# Set X range.Using left and right variables makes it easy to change the range.
#
left = dt.date(2020, 3, 15)
right = dt.date(2020, 7, 15)

# Create scatter plot of Positive Cases
#
plt.scatter(
   x, y, c = "blue", edgecolor = "black",
   linewidths = 1, marker = "o", alpha = 0.8, label = "Total Positive Tested"
)

# Format the date into months & days
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))

# Change the tick interval
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval = 30))

# Puts x - axis labels on an angle
plt.gca().xaxis.set_tick_params(rotation = 30)

# Changes x - axis range
plt.gca().set_xbound(left, right)

plt.show()

Suggestion : 2

Updated: September 11, 2020,Time period B: 2013-08-01 to 2013-11-01,Time period A: 2012-08-01 to 2012-11-01

# Import necessary packages
import os
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates
import DateFormatter
import seaborn as sns
import pandas as pd
import earthpy as et

# Handle date time conversions between pandas and matplotlib
from pandas.plotting
import register_matplotlib_converters
register_matplotlib_converters()

# Use white grid plot background from seaborn
sns.set(font_scale = 1.5, style = "whitegrid")
# Download the data
data = et.data.get_data('colorado-flood')
# Set working directory
os.chdir(os.path.join(et.io.HOME, 'earth-analytics'))

# Define relative path to file with daily precip
file_path = os.path.join("data", "colorado-flood",
   "precipitation",
   "805325-precip-dailysum-2003-2013.csv")
# Import data using datetime and no data value
precip_2003_2013_daily = pd.read_csv(file_path,
   parse_dates = ['DATE'],
   index_col = ['DATE'],
   na_values = ['999.99'])
# Subset data to June - Aug 2005
precip_june_aug_2005 = precip_2003_2013_daily['2005-06-01': '2005-08-31']

precip_june_aug_2005.head()
# Create figure and plot space
fig, ax = plt.subplots(figsize = (12, 12))

# Add x - axis and y - axis
ax.bar(precip_june_aug_2005.index.values,
   precip_june_aug_2005['DAILY_PRECIP'],
   color = 'purple')

# Set title and labels
for axes
ax.set(xlabel = "Date",
   ylabel = "Precipitation (inches)",
   title = "Daily Total Precipitation\nJune - Aug 2005 for Boulder Creek")

plt.show()

Suggestion : 3

Matplotlib date plotting is done by converting date instances into days since an epoch (by default 1970-01-01T00:00:00). The matplotlib.dates module provides the converter functions date2num and num2date that convert datetime.datetime and numpy.datetime64 objects to and from Matplotlib's internal representation. These data types are registered with the unit conversion mechanism described in matplotlib.units, so the conversion happens automatically for the user. The registration process also sets the default tick locator and formatter for the axis to be AutoDateLocator and AutoDateFormatter., Formatting date ticks using ConciseDateFormatter , Demonstrates plotting contour (level) curves in 3D using the extend3d option , Labeling ticks using engineering notation

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook

# Load a numpy structured array from yahoo csv data with fields date, open,
# close, volume, adj_close from the mpl - data / example directory.This array
# stores the date as an np.datetime64 with a day unit('D') in the 'date'
# column.
data = cbook.get_sample_data('goog.npz', np_load = True)['price_data']

fig, axs = plt.subplots(3, 1, figsize = (6.4, 7), constrained_layout = True)
# common to all three:
   for ax in axs:
   ax.plot('date', 'adj_close', data = data)
# Major ticks every half year, minor ticks every month,
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth = (1, 7)))
ax.xaxis.set_minor_locator(mdates.MonthLocator())
ax.grid(True)
ax.set_ylabel(r 'Price [\$]')

# different formats:
   ax = axs[0]
ax.set_title('DefaultFormatter', loc = 'left', y = 0.85, x = 0.02, fontsize = 'medium')

ax = axs[1]
ax.set_title('ConciseFormatter', loc = 'left', y = 0.85, x = 0.02, fontsize = 'medium')
ax.xaxis.set_major_formatter(
   mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))

ax = axs[2]
ax.set_title('Manual DateFormatter', loc = 'left', y = 0.85, x = 0.02,
   fontsize = 'medium')
# Text in the x axis will be displayed in 'YYYY-mm'
format.
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
# Rotates and right - aligns the x labels so they don 't crowd each other.
for label in ax.get_xticklabels(which = 'major'):
   label.set(rotation = 30, horizontalalignment = 'right')

plt.show()

Suggestion : 4

For example, plot the XDates and YNumsForXDates arrays. Then change the x-axis limits to June 20 and July 7, 2021, using xlim. The plot displays new tick values.,For example, plot XDates and YNumsForXDates. Then create a data tip by clicking on the plot.,For example, plot the XTimes and YNumsForXTimes arrays. Then specify tick values at 0, 60, and 120 seconds by using xticks.,For example, the XLim and XTick properties associated with the plot of XDates and YNumsForXDates store datetime values. Get the Axes object for the plot and display these properties.

XDates = [datetime(2021, 6, 1: 30) datetime(2021, 7, 1: 31)];
YNumsForXDates = sin(0: 0.1: 6);
plot(XDates, YNumsForXDates)
XTimes = seconds(0: 120);
YNumsForXTimes = cos(0: 0.05: 6);
plot(XTimes, YNumsForXTimes)
plot(XDates, YNumsForXDates)
xlim([datetime("2021-06-20") datetime("2021-07-07")])
xlim([datetime("2021-06-20") datetime("2021-06-22")])
plot(XTimes, YNumsForXTimes)
xticks(seconds([0 60 120]))
plot(XDates, YNumsForXDates)
xtickformat("yyyy-MM-dd")

Suggestion : 5

I'm writing this for python-django, if that's relevant. ,I'm trying to plot a graph of dates on the x-axis and values on the y-axis. It works fine, except that I can't get the range of the x-axis to be appropriate. The x-axis range is always Jan 2012 to Jan 2016, despite my dates being from today. I am even specifying that xlim should be the first and last date. ,  › Speeding up python code that has to go through entire list,  › Python class with datetime now when instantiated


 import datetime
 import matplotlib.pyplot as plt x = [datetime.date(2014, 1, 29), datetime.date(2014, 1, 29), datetime.date(2014, 1, 29)] y = [2, 4, 1] fig, ax = plt.subplots() ax.plot_date(x, y) ax.set_xlim([x[0], x[-1]]) canvas = FigureCanvas(plt.figure(1)) response = HttpResponse(content_type = 'image/png') canvas.print_png(response) return response

import datetime
import matplotlib.pyplot as plt x = [datetime.date(2014, 1, 29)] * 3 y = [2, 4, 1] fig, ax = plt.subplots() ax.plot_date(x, y, markerfacecolor = 'CornflowerBlue', markeredgecolor = 'white') fig.autofmt_xdate() ax.set_xlim([datetime.date(2014, 1, 26), datetime.date(2014, 2, 1)]) ax.set_ylim([0, 5])
import datetime
import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = [datetime.date(2021, 1, 1), datetime.date(2021, 1, 3), datetime.date(2021, 1, 5), datetime.date(2021, 1, 7)] y = [1, 3, 5, 7] fig, ax = plt.subplots() ax.plot_date(x, y, markerfacecolor = 'green', markeredgecolor = 'red', ms = 7) fig.autofmt_xdate() ax.set_xlim([datetime.date(2020, 12, 31), datetime.date(2021, 1, 8)]) ax.set_ylim([0, 8]) plt.show()