英文:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论