python pandas timeseries plots,如何在ts.plot()之外设置xlim和xticks?

2024-04-19 01:57:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

有时有效,但如果熊猫将xaxis格式化为从纪元开始的月份,而不是天,这将很难失败。

有没有人知道熊猫是如何将日期转换成xaxis,然后以同样的方式转换我的xlim的?

谢谢。


Tags: 绘图pandasplotfigpltax例程figure
1条回答
网友
1楼 · 发布于 2024-04-19 01:57:40

如果我使用pd.Timestamp值设置x轴限制,它对我(pandas为0.16.2)有效。

示例:

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)

结果:

Plot of time series with x-axis limits manually adjusted.

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

相关问题 更多 >