如何使用MatPlotLib中的数据时间更改x轴的范围? [英] How do I change the range of the x-axis with datetimes in MatPlotLib?

查看:950
本文介绍了如何使用MatPlotLib中的数据时间更改x轴的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制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(响应)
返回响应

这里是输出:

解决方案

编辑:



从OP中查看了实际数据后,所有值都与日期/时间相同。所以matplotlib自动缩放x轴。您仍然可以使用 datetime 对象






手动设置x轴限制p>如果我在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] )

我得到:





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


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:

解决方案

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

I get:

And the axes limits match the dates that I specified.

这篇关于如何使用MatPlotLib中的数据时间更改x轴的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆