有一個時間序列資料,比如下面這些。
Time Order nun
0 2/10/2019 200
1 3/3/2019 150
2 3/15/2019 50
3 3/25/2019 100
4 4/16/2019 90
5 4/17/2019 190
6 5/6/2019 120
7 5/18/2019 110
如何根據每月值的總和生成時間序列條形圖。

uj5u.com熱心網友回復:
您可以設定Time為索引并用于pd.Grouper(freq='M')按月分組
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df['Time'] = pd.to_datetime(df['Time'])
out = df.set_index('Time').groupby(pd.Grouper(freq='M'))['Order number'].sum()
fig, ax = plt.subplots()
bars = ax.bar(out.index, out)
ax.bar_label(bars)
ax.set_xlabel("Time (month)")
ax.set_ylabel("Order number")
ax.set_xticks(out.index)
ax.set_yticks(range(200, 800, 200))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
plt.show()

酒吧之所以這么細,是因為酒吧一個月只需要一天。您可以改用字串使其正常。
df['Time'] = pd.to_datetime(df['Time']).dt.strftime('%b %Y')
out = df.groupby('Time')['Order number'].sum()
fig, ax = plt.subplots()
bars = ax.bar(out.index, out)
ax.bar_label(bars)
ax.set_xlabel("Time (month)")
ax.set_ylabel("Order number")
ax.set_xticks(out.index)
ax.set_yticks(range(200, 800, 200))
plt.show()

uj5u.com熱心網友回復:
import seaborn as sns
import matplotlib.pyplot as plt
df['Time'] = pd.to_datetime(df['Time'])
plotme = df.resample('M', on='Time').sum()
sns.barplot(y=plotme['Order nun'], x=plotme['Time'].dt.strftime('%b %Y'))
plt.show()
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474863.html
標籤:Python 熊猫 matplotlib 海运 条形图
