【问题标题】:How do I change the range of the x-axis with datetimes in matplotlib?如何在 matplotlib 中使用日期时间更改 x 轴的范围?
【发布时间】:2014-01-29 05:53:05
【问题描述】:

我正在尝试在 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

这是输出:

【问题讨论】:

  • 我们需要查看您的一些数据来运行您的示例。简短的自助式答案是在将数据添加到轴后调用 print(ax.get_xlim()) 并查看返回的值。然后,您可以根据需要调整它们。

标签: python django date matplotlib


【解决方案1】:

编辑:

查看来自 OP 的实际数据后,所有值都在相同的日期/时间。所以 matplotlib 会自动缩小 x 轴。您仍然可以使用 datetime 对象手动设置 x 轴范围


如果我在 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])

我明白了:

坐标轴范围与我指定的日期相匹配。

【讨论】:

  • @aled1027 您的所有积分都在同一时间。这真的是您正在使用的数据吗?
  • 感谢您的帮助。我把它修好了。当我从数据库中检索数据时,数据没有没有小时、分钟和秒。
  • 这个解决方案可以使用ax.set_xlim([datetime.datetime(2014, 1, 28, 23, 50, 0), datetime.datetime(2014, 1, 29, 0, 10, 0)])datetime.date推广到datetime.datetime。也可以使用import pandas as pd 并使用ax.set_xlim([pd.to_datetime('2014-01-28 23:50:00'), pd.to_datetime('2014-01-29 00:10:00')])
  • @Qaswed 不确定这是如何“概括”的,但是是的,datedatetime 对象都可以工作
  • @PaulH “泛化”,即datetime 允许datetime(2014, 1, 28, 23, 50, 0) datetime(2014, 1, 29, 0, 0, 0),但(据我所知)date 只允许@ 987654335@.
【解决方案2】:

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

【讨论】:

  • 关于这个答案使用ax.set_xbound ()而不是通常的ax.set_xlim (),(一些)澄清here
猜你喜欢
  • 2019-12-19
  • 2013-08-01
  • 1970-01-01
  • 2016-10-19
  • 2019-05-01
  • 1970-01-01
  • 2015-05-02
  • 2017-10-13
相关资源
最近更新 更多