我对 pandas 很陌生,我在 StackOverflow 上搜索了许多与每年更改 xtick 标签类似的问题,但它们都不同并没有解决我的问题,所以我决定问自己的问题。
这是我的问题。我有一个模拟数据框,我想在 x 轴上绘制每年的 xticks。
import numpy as np
import pandas as pd
df = pd.DataFrame({'date': pd.date_range('1991-01-01','2019-01-01')}).set_index('date')
df['value'] = np.random.randn(len(df))
df.plot()
这给出: Xticks ==> 1995 2000 2005 等 但我想要==> 1991 1992 ... 2019
如何做到这一点?
到目前为止我已经尝试过:
import matplotlib
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
fig,ax = plt.subplots()
df.plot(ax=ax)
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator(base=1))
# ax.xaxis.set_minor_locator(matplotlib.dates.YearLocator(base=1))
# ax.set_xticklabels(list(df.index.time))
这只是 2005 年的 xtick,到目前为止还没有任何效果。
我查看的链接: -Changing xticks in a pandas plot -Python: Change the time on xticks for Pandas Plot -https://matplotlib.org/3.1.1/api/dates_api.html
最佳答案
您需要使用 x_compat=True 参数让 pandas 选择与 matplotlib.dates 定位器和格式化程序兼容的单位。
df.plot(ax=ax, x_compat=True)
完整代码:
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
df = pd.DataFrame({'date': pd.date_range('1991-01-01','2019-01-01')}).set_index('date')
df['value'] = np.random.randn(len(df))
fig,ax = plt.subplots()
df.plot(ax=ax, x_compat=True)
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator(base=1))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
plt.show()
关于python - 如何将pandas时间序列图中的xticks更改为每年间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57126647/