如何在matplotlib中使用日期时间更改x轴的范围?

时间:2014-01-29 05:53:06

标签: python django date matplotlib

我正在尝试绘制x轴上的日期图和y轴上的值。它工作正常,除了我不能使x轴的范围合适。 x轴范围始终是2012年1月至2016年1月,尽管我的日期是从今天开始。我甚至指定xlim应该是第一个和最后一个日期。

我正在为python-django写这个,如果那是相关的。

 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

这是输出: enter image description here

2 个答案:

答案 0 :(得分:21)

编辑:

从OP看到实际数据后,所有值都处于相同的日期/时间。所以matplotlib会自动缩放x轴。您仍然可以使用datetime个对象

手动设置x轴限制

如果我在matplotlib v1.3.1上做了类似的事情:

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

我明白了:

enter image description here

轴限制与我指定的日期匹配。

答案 1 :(得分:4)

在Paul H的解决方案的帮助下,我能够更改基于时间的x轴的范围。

对于其他初学者,这是一个更通用的解决方案。

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