[英]How to create a grouped bar chart (by month and year) on the x-axis and values on the y-axis using matplotlib.pyplot?
[英]Using year-week column as x-axis for bar chart in matplotlib
我嘗試使用 plot bar plot
和matplotlib
來顯示每周匯總數字隨時間的變化(我的數據集大約有 1000 周)。 通常,當我 plot 這樣的時間序列時,我有每日數據,我用pd.to_datetime()
轉換日期。 但在每周的情況下,不知道如何指定格式以獲得准確的x-axis
標簽,其中包含年份而不是相互重疊的周。
這將是一個簡單的數據集示例:
YearWeek Output
0 2022-01 7.3
1 2022-02 5.3
2 2022-03 7.2
3 2022-04 4.8
4 2022-05 5.8
5 2022-06 9.2
6 2022-07 5.3
7 2022-08 5.3
8 2022-09 7.5
9 2022-10 9.2
10 2022-11 5.4
11 2022-12 4.8
在更多周的情況下, x-axis
不可讀並且標簽彼此重疊。 我試圖只獲得年度標簽。
為了重現性:
import pandas as pd
import matplotlib.pyplot as plt
df1 = pd.DataFrame({
'YearWeek':['2022-01', '2022-02', '2022-03', '2022-04', '2022-05', '2022-06', '2022-07', '2022-08', '2022-09', '2022-10', '2022-11', '2022-12'],
'Output':[7.3, 5.3, 7.2, 4.8, 5.8, 9.2, 5.3, 5.3, 7.5, 9.2, 5.4, 4.8]})
plt.bar(df1['YearWeek'], df1['Output'])
非常感謝!
Edit1:添加plt.xticks(df1['YearWeek'],df1['YearWeek'].str[:4])
以在 x 軸上僅顯示年份而不是年份周。
Edit2:x 軸每年只顯示一次。
您可以使用plt.xticks(rotation=90)
將 x 軸刻度旋轉 90 度或 45 度。
例如:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df1 = pd.DataFrame({
'YearWeek':['2021-01', '2021-02', '2021-03', '2021-04', '2021-05', '2021-06', '2021-07', '2021-08', '2021-09', '2021-10', '2021-11', '2021-12', '2022-01', '2022-02', '2022-03', '2022-04', '2022-05', '2022-06', '2022-07', '2022-08', '2022-09', '2022-10', '2022-11', '2022-12'],
'Output':[6.3, 5.3, 7.2, 4.8, 8.8, 9.2, 5.3, 5.3, 4.5, 9.2, 5.4, 4.8, 7.3, 5.3, 8.2, 4.8, 5.8, 9.2, 5.3,2.3, 7.5, 9.2, 5.4, 9.8]})
df1['Year'] = df1['YearWeek'].str[:4]
plt.bar(df1['YearWeek'], df1['Output'])
# plt.xticks(rotation=90)
plt.xticks(df1['YearWeek'],df1['Year'])
plt.xticks(np.arange(6, len(df1), 12))
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.