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

6 投票
1 回答
5643 浏览
提问于 2025-04-18 12:55

当我绘制完整的数据时,一切都正常,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 个回答

7

我有一个方法可以让标签看起来更统一,不过要注意,这个方法也会在“更大范围”的时间图上显示时间。

下面的代码使用了 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

撰写回答