调整每月条形图的标签

huangapple go评论64阅读模式
英文:

Adjust labels for monthly bar plot

问题

我有一个Series monthCount

调整每月条形图的标签

我想要将其绘制成条形图。可以使用monthCount.plot.bar()来实现:

调整每月条形图的标签

然而,我更希望为这些条形图使用不同的标签。例如,"January 2022","February 2022"等会更好。甚至可以将年份省略并放在上方作为标题。如何以这种方式更改条形图的标签?

英文:

I have a Series monthCount:

调整每月条形图的标签

And I want to plot it as bar plot. This works using monthCount.plot.bar():

调整每月条形图的标签

However, I would prefer different labels for the bars. "January 2022", "February 2022" and so on would be much better. Even the year could be dropped and put as caption above. How do I change the labels in that way for the bars?

答案1

得分: 2

你可以定义自己的标签并设置旋转:

ax = monthCount.plot.bar()

labels = monthCount.index.strftime('%B %Y')
ax.set_xticklabels(labels, rotation=45, ha='right', rotation_mode='anchor')
plt.tight_layout()
plt.show()

输出:

调整每月条形图的标签

最小可复现示例:

import pandas as pd
import matplotlib.pyplot as plt

data = {pd.Timestamp('2022-01-01 00:00:00'): 31,
        pd.Timestamp('2022-02-01 00:00:00'): 28,
        pd.Timestamp('2022-03-01 00:00:00'): 31,
        pd.Timestamp('2022-04-01 00:00:00'): 28,
        pd.Timestamp('2022-05-01 00:00:00'): 6,
        pd.Timestamp('2022-06-01 00:00:00'): 0,
        pd.Timestamp('2022-07-01 00:00:00'): 0,
        pd.Timestamp('2022-08-01 00:00:00'): 0,
        pd.Timestamp('2022-09-01 00:00:00'): 15,
        pd.Timestamp('2022-10-01 00:00:00'): 19,
        pd.Timestamp('2022-11-01 00:00:00'): 30,
        pd.Timestamp('2022-12-01 00:00:00'): 31}
monthCount = pd.Series(data).rename_axis('date')
英文:

You can define your own labels and set the rotation:

ax = monthCount.plot.bar()

labels = monthCount.index.strftime('%B %Y')
ax.set_xticklabels(labels, rotation=45, ha='right', rotation_mode='anchor')
plt.tight_layout()
plt.show()

Output:

调整每月条形图的标签

Minimal Reproducible Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {pd.Timestamp('2022-01-01 00:00:00'): 31,
        pd.Timestamp('2022-02-01 00:00:00'): 28,
        pd.Timestamp('2022-03-01 00:00:00'): 31,
        pd.Timestamp('2022-04-01 00:00:00'): 28,
        pd.Timestamp('2022-05-01 00:00:00'): 6,
        pd.Timestamp('2022-06-01 00:00:00'): 0,
        pd.Timestamp('2022-07-01 00:00:00'): 0,
        pd.Timestamp('2022-08-01 00:00:00'): 0,
        pd.Timestamp('2022-09-01 00:00:00'): 15,
        pd.Timestamp('2022-10-01 00:00:00'): 19,
        pd.Timestamp('2022-11-01 00:00:00'): 30,
        pd.Timestamp('2022-12-01 00:00:00'): 31}
monthCount = pd.Series(data).rename_axis('date')

huangapple
  • 本文由 发表于 2023年6月22日 16:24:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定