如何在pandas条形图上设置X轴标签的格式

oknwwptz  于 2023-09-29  发布在  其他
关注(0)|答案(1)|浏览(100)

运行以下代码:

covid = pd.read_csv("https://covid.ourworldindata.org/data/owid-covid-data.csv")
covid.set_index("date", inplace=True)
covid.index = pd.to_datetime(covid.index)
covid[covid.location=="Denmark"].new_cases_smoothed_per_million.plot()

你会得到格式很好的X轴标签:

使用bar方法,您不会得到格式良好的X轴标签:

covid[covid.location=="Denmark"].new_cases_smoothed_per_million.plot.bar()

如何在条形图上获得格式良好的X轴标签?

6vl6ewon

6vl6ewon1#

你可以试试这样的方法:

covid = pd.read_csv("https://covid.ourworldindata.org/data/owid-covid-data.csv")
covid.set_index("date", inplace=True)
covid.index = pd.to_datetime(covid.index)
df = covid.loc[covid.location=="Denmark", 'new_cases_smoothed_per_million']
g =  df.groupby(pd.Grouper(freq='M')).sum()
ax = g.plot.bar(figsize=(15,6), rot=0)
def line_format(label):
    """
    Convert time label to the format of pandas line plot
    """
    month = label.month_name()[:3]
    if month == 'Jan':
        month += f'\n{label.year}'
    return month

ax.set_xticklabels(map(line_format, g.index), fontsize=8);

输出量:

相关问题