我有一個包含這些資料的資料框,并想用 x 軸標簽為月的條形圖繪制它
import pandas as pd
data = {'Birthday': ['1900-01-31', '1900-02-28', '1900-03-31', '1900-04-30', '1900-05-31', '1900-06-30', '1900-07-31', '1900-08-31', '1900-09-30', '1900-10-31', '1900-11-30', '1900-12-31'],
'Players': [32, 25, 27, 19, 27, 18, 18, 21, 23, 21, 26, 23]}
df = pd.DataFrame(data)
Birthday Players
1900-01-31 32
1900-02-28 25
1900-03-31 27
1900-04-30 19
1900-05-31 27
1900-06-30 18
1900-07-31 18
1900-08-31 21
1900-09-30 23
1900-10-31 21
1900-11-30 26
1900-12-31 23
這就是我所擁有的
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig = plt.figure(figsize=(12, 7))
locator = mdates.MonthLocator()
fmt = mdates.DateFormatter('%b')
X = plt.gca().xaxis
X.set_major_locator(locator)
X.set_major_formatter(fmt)
plt.bar(month_df.index, month_df.Players, color = 'maroon', width=10)
但結果是這個標簽從二月而不是一月開始

uj5u.com熱心網友回復:
- 條形圖 x 軸刻度位置為 0 索引,而不是日期時間
- 此解決方案適用于任何具有離散軸(例如條形、直方圖、熱度等)的圖。
- 與此
- 如果有很多重復的月份,必須在其中聚合資料,然后使用
uj5u.com熱心網友回復:
我對 matplotlib.dates 不熟悉,但是因為您使用的是 Pandas,所以有一些簡單的方法可以使用 Pandas 完成您需要的操作。
這是我的代碼:
import pandas as pd import calendar from matplotlib import pyplot as plt # data data = {'Birthday': ['1900-01-31', '1900-02-28', '1900-03-31', '1900-04-30', '1900-05-31', '1900-06-30', '1900-07-31', '1900-08-31', '1900-09-30', '1900-10-31', '1900-11-30', '1900-12-31'], 'Players': [32, 25, 27, 19, 27, 18, 18, 21, 23, 21, 26, 23]} df = pd.DataFrame(data) # convert column to datetime df["Birthday"] = pd.to_datetime(df["Birthday"], format="%Y-%m-%d") # groupby month and plot bar plot df.groupby(df["Birthday"].dt.month).sum().plot(kind="bar", color = "maroon") # set plot properties plt.xlabel("Birthday Month") plt.ylabel("Count") plt.xticks(ticks = range(0,12) ,labels = calendar.month_name[1:]) # show plot plt.show()輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369030.html標籤:Python 熊猫 数据框 matplotlib 条形图
- 如果有很多重復的月份,必須在其中聚合資料,然后使用
