python - 重新采样后无法在 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 ()
解决方案
作为替代方案,这可能对您有用:
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()
另请参阅此问题的答案。
推荐阅读
- java - Mac上有_JAVA_OPTIONS吗?
- python - fromkeys 方法的意外结果
- swift - SwiftUI - 数组中只有一个对象属性为真
- c++ - Qt Quick2 为单例类类型创建 qmlRegisterSingletonType
- python - 使用 pandas 对行进行子集化
- android - 如果 edittext 在 TextInputlayout 内,将 drawableLeft 添加到 EditText 会使提示向右移动。当 proguard 启用时
- python - 用户存在但无法使用 simpleJWT 和 Django Admin 进行身份验证
- python - 计算 df 的平均值,但如果 =>1 的值与该平均值相差 >20%,则平均值设置为 NaN
- c# - 如何为 ASP.NET Core API 设置 OAuth2 不记名令牌?
- javascript - js转义特殊字符