如何自定义Pandas日期时间戳@ x轴

时间:2014-07-11 08:21:51

标签: python date time plot pandas

当我绘制完整数据时工作正常并在x轴上显示日期:

1

当我放大特定部分观看时:
2

情节只显示时间而不是日期,我明白用较少的点不能显示不同的日期,但即使图表被缩放,如何显示日期或设置日期格式?

dataToPlot = pd.read_csv(fileName, names=['time','1','2','3','4','plotValue','6','7','8','9','10','11','12','13','14','15','16'], 
                             sep=',', index_col=0, parse_dates=True, dayfirst=True)
dataToPlot.drop(dataToPlot.index[0])
startTime = dataToPlot.head(1).index[0]
endTime = dataToPlot.tail(1).index[0]
ax = pd.rolling_mean(dataToPlot_plot[startTime:endTime][['plotValue']],mar).plot(linestyle='-', linewidth=3,  markersize=9, color='#FECB00')

提前致谢!

1 个答案:

答案 0 :(得分:6)

我有一个解决方案,使标签看起来一致,但请记住,它还将包括“更大规模”时间图上的时间。

以下代码使用matplotlib.dates功能为x轴选择日期格式。请注意,由于我们使用的是matplotlib格式,因此您无法简单地使用df.plot,而必须使用plt.plot_date并将索引转换为正确的格式。

import pandas as pd

import matplotlib.pyplot as plt
from matplotlib import dates

# Generate some random data and plot it

time = pd.date_range('07/11/2014', periods=1000, freq='5min')
ts = pd.Series(pd.np.random.randn(len(time)), index=time)

fig, ax = plt.subplots()

ax.plot_date(ts.index.to_pydatetime(), ts.data)

# Create your formatter object and change the xaxis formatting.

date_fmt = '%d/%m/%y %H:%M:%S'

formatter = dates.DateFormatter(date_fmt)
ax.xaxis.set_major_formatter(formatter)

plt.gcf().autofmt_xdate()

plt.show()

显示完全缩小图

的示例

enter image description here

显示放大的情节的示例。

enter image description here