Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the range of the x-axis with datetimes in matplotlib?

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.

I'm writing this for python-django, if that's relevant.

 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 

And here is the output: enter image description here

like image 242
aled1027 Avatar asked Jan 29 '14 05:01

aled1027


People also ask

How do you change the range of the X-axis in MatPlotLib?

MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.

How do you change the axis range on PLT?

To plot a line graph, use the plot() function. To set range of x-axis and y-axis, use xlim() and ylim() function respectively. To add a title to the plot, use the title() function. To add label at axes, use xlabel() and ylabel() functions.


2 Answers

Edit:

Having seen actual data from the OP, all of the values are at the same date/time. So matplotlib is automatically zooming the x-axis out. You can still manually set the x-axis limits with datetime objects


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]) 

I get:

enter image description here

And the axes limits match the dates that I specified.

like image 71
Paul H Avatar answered Sep 28 '22 10:09

Paul H


With help from Paul H's solution, I was able to change the range of my time-based x-axis.

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() 

enter image description here

like image 45
Heather Claxton Avatar answered Sep 28 '22 12:09

Heather Claxton