简体   繁体   English

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

[英]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.我试图在 x 轴上绘制日期图,在 y 轴上绘制值。 It works fine, except that I can't get the range of the x-axis to be appropriate.它工作正常,除了我无法获得合适的 x 轴范围。 The x-axis range is always Jan 2012 to Jan 2016, despite my dates being from today.尽管我的日期是从今天开始,但 x 轴范围始终是 2012 年 1 月到 2016 年 1 月。 I am even specifying that xlim should be the first and last date.我什至指定 xlim 应该是第一个和最后一个日期。

I'm writing this for python-django, if that's relevant.如果相关,我正在为 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

And here is the output:这是输出:在此处输入图片说明

Edit:编辑:

Having seen actual data from the OP, all of the values are at the same date/time.从 OP 看到实际数据后,所有值都在同一日期/时间。 So matplotlib is automatically zooming the x-axis out.所以 matplotlib 会自动缩小 x 轴。 You can still manually set the x-axis limits with datetime objects您仍然可以使用datetime对象手动设置 x 轴限制


If I do something like this on matplotlib v1.3.1:如果我在 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:我得到:

在此处输入图片说明

And the axes limits match the dates that I specified.轴限制与我指定的日期相匹配。

With help from Paul H's solution, I was able to change the range of my time-based x-axis.在 Paul H 的解决方案的帮助下,我能够更改基于时间的 x 轴的范围。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM