python pandas时间序列图,如何在ts.plot()之外设置xlim和xticks?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27425015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python pandas timeseries plots, how to set xlim and xticks outside ts.plot()?
提问by jf328
fig = plt.figure()
ax = fig.gca()
ts.plot(ax=ax)
I know I can set xlim inside pandas plotting routine: ts.plot(xlim = ...), but how to change it after pandas plotting is done?
我知道我可以在 Pandas 绘图程序中设置 xlim:ts.plot(xlim = ...),但是在 Pandas 绘图完成后如何更改它?
ax.set_xlim(( t0.toordinal(), t1.toordinal() )
works sometimes, but if pandas is formatting the xaxis as months from epoch, not days, this will fail hard.
有时工作,但如果熊猫将 xaxis 格式化为纪元后的几个月,而不是几天,这将很难失败。
Is there anyway to know how pandas has converted the dates to xaxis and then convert my xlim in the same way?
无论如何要知道熊猫如何将日期转换为 xaxis,然后以相同的方式转换我的 xlim?
Thanks.
谢谢。
采纳答案by cilix
It works for me (with pandas 0.16.2) if I set the x-axis limits using pd.Timestamp
values.
如果我使用pd.Timestamp
值设置 x 轴限制,它对我有用(使用 Pandas 0.16.2)。
Example:
例子:
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)
Result:
结果:
Note that if you plot multiple time series in the same figure then make sure to set xlim/ylim afterthe last ts.plot()
command, otherwise pandas will automatically reset the limits to match the contents.
请注意,如果您在同一图中绘制多个时间序列,请确保在最后一个命令之后设置 xlim/ylim ts.plot()
,否则Pandas将自动重置限制以匹配内容。