繁体   English   中英

将年份设置为 matplotlib 中的 x 标签

[英]set year to the x labels in matplotlib

我有一个 dataframe 如下

    Out[125]: 
         Google Tends: unem. insurance  Unemp. Rate
YM                                                 
2004-01                           0.34     0.270968
2004-02                           0.33     0.270968
2004-03                           0.00     0.270968
2004-04                           0.17     0.270968
2004-05                           0.15     0.270968

我想要 plot 并且我想要将年份编号写在 x 轴下方作为数据的 label。 这是我找到的代码

years = mdates.YearLocator()  
years_fmt = mdates.DateFormatter('%Y')


fig, ax = plt.subplots()

ax.plot(end.index, end['Google Tends: unem. insurance'])

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.format_xdata = mdates.DateFormatter('%Y')

plt.show()

我没有收到错误消息,但标签也没有

在此处输入图像描述

  • YM必须首先转换为日期时间格式。 目前,日期只是一个str类型。
    • YM应在任何.groupby之前转换为日期时间。
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

data = {'YM': ['2004-01', '2004-02', '2004-03', '2004-04', '2004-05', '2005-01', '2006-01'],
        'Google Tends: unem. insurance': [0.34, 0.33, 0.0, 0.17, 0.15, 0.12, 0.34],
        'Unemp. Rate': [0.270968, 0.270968, 0.270968, 0.270968, 0.270968, 0.270968, 0.270968]}

df = pd.DataFrame(data)

        YM  Google Tends: unem. insurance  Unemp. Rate
0  2004-01                           0.34     0.270968
1  2004-02                           0.33     0.270968
2  2004-03                           0.00     0.270968
3  2004-04                           0.17     0.270968
4  2004-05                           0.15     0.270968
5  2005-01                           0.12     0.270968
6  2006-01                           0.34     0.270968

# convert YM to datetime
df.YM = pd.to_datetime(df.YM, format='%Y-%m')

# plot
years = mdates.YearLocator()  
years_fmt = mdates.DateFormatter('%Y')

fig, ax = plt.subplots()
ax.plot('YM', 'Google Tends: unem. insurance', data=df)

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM