首页 > 解决方案 > 重新采样后无法在 Pandas 中格式化 X 刻度

问题描述

我已经从每月系列中重新采样数据以绘制年度平均值。但是,年份刻度在 X 轴上以以下格式显示:

正确的情节

但是,我只想显示年份,而不是整个时间戳。但是以下代码无法正确绘制图形。

ax = umtmvsDF.resample('A').mean().plot.bar(title='Average value per year',grid=True,color=(.21,.42,.12),figsize=(12,10))
    ax.set(xlabel=Constants.TIME,ylabel=Constants.USD)
    ax.xaxis.set_major_formatter(dates.DateFormatter('%Y'))
    plt.show() 

不正确的情节

此代码显示所有刻度都等于 1970。我在这里做错了什么?

编辑解决方案:: @Rene 分享了最终解决问题的链接。它提供了 1970 出现在第二张图中的原因。

修改后的代码

tempDF3 = umtmvsDF.resample ( 'A' ).mean ()
ax = tempDF3.plot.bar ( title='Average value per year', grid=True, color=(.21, .42, .12),
                                                  figsize=(12, 10) )
ax.set ( xlabel=Constants.TIME, ylabel=Constants.USD )

ticklabels = ['']*len(tempDF3.index)
ticklabels[::5] = [item.strftime('%Y') for item in tempDF3.index[::5]]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.gcf().autofmt_xdate()
plt.show ()

解决方案图在此处输入图像描述

标签: pythonpandasdataframematplotlib

解决方案


作为替代方案,这可能对您有用:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

umtmvsDF = pd.Series(
    data = np.random.randint(0, high=100, size=132, dtype=int), 
    index = pd.date_range(start='1/1/1980', end='1/1/1991', freq='M')
)

df = umtmvsDF.resample('A').mean()

ax = df.plot.bar(
    title = 'Average value per year',
    grid = True,
    color = (.21,.42,.12),
    figsize = (12,10)
)

ax.set_xticklabels(df.index.strftime('%Y'))

plt.show()

在此处输入图像描述

另请参阅此问题的答案。


推荐阅读