python pandas时间序列图,如何在ts.plot()之外设置xlim和xticks? [英] python pandas timeseries plots, how to set xlim and xticks outside ts.plot()?

查看:261
本文介绍了python pandas时间序列图,如何在ts.plot()之外设置xlim和xticks?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fig = plt.figure()
ax = fig.gca()
ts.plot(ax=ax)

我知道我可以在熊猫绘图程序ts.plot(xlim = ...)中设置xlim,但是在熊猫绘图完成后如何更改它?

I know I can set xlim inside pandas plotting routine: ts.plot(xlim = ...), but how to change it after pandas plotting is done?

ax.set_xlim(( t0.toordinal(), t1.toordinal() )

有时可以工作,但是如果熊猫将xaxis格式设置为从纪元开始数月而不是几天,那么这将很难失败.

works sometimes, but if pandas is formatting the xaxis as months from epoch, not days, this will fail hard.

有没有办法知道熊猫如何将日期转换为xaxis,然后以相同的方式转换我的xlim?

Is there anyway to know how pandas has converted the dates to xaxis and then convert my xlim in the same way?

谢谢.

推荐答案

如果我使用pd.Timestamp值设置x轴限制,则对我有效(使用熊猫0.16.2).

It works for me (with pandas 0.16.2) if I set the x-axis limits using pd.Timestamp values.

示例:

import pandas as pd

# Create a random time series with values over 100 days
# starting from 1st March.
N = 100
dates = pd.date_range(start='2015-03-01', periods=N, freq='D')
ts = pd.DataFrame({'date': dates,
                   'values': np.random.randn(N)}).set_index('date')

# Create the plot and adjust x/y limits. The new x-axis
# ranges from mid-February till 1st July.
ax = ts.plot()
ax.set_xlim(pd.Timestamp('2015-02-15'), pd.Timestamp('2015-07-01'))
ax.set_ylim(-5, 5)

结果:

请注意,如果您在同一图中绘制多个时间序列,请确保在最后一个ts.plot()命令之后将xlim/ylim 设置为,否则熊猫将自动重置限制以匹配内容.

Note that if you plot multiple time series in the same figure then make sure to set xlim/ylim after the last ts.plot() command, otherwise pandas will automatically reset the limits to match the contents.

这篇关于python pandas时间序列图,如何在ts.plot()之外设置xlim和xticks?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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