給定一個小資料集,如下所示:
date value type
0 2021-07-31 6.32 1
1 2021-08-31 5.93 1
2 2021-09-30 5.43 2
3 2021-10-30 4.72 2
4 2021-11-30 4.23 3
5 2021-12-31 3.96 3
或者:
df = pd.DataFrame({'date': {0: '2021-07-31',
1: '2021-08-31',
2: '2021-09-30',
3: '2021-10-30',
4: '2021-11-30',
5: '2021-12-31'},
'value': {0: 6.32, 1: 5.93, 2: 5.43, 3: 4.72, 4: 4.23, 5: 3.96},
'type': {0: 1, 1: 1, 2: 2, 3: 2, 4: 3, 5: 3}})
我希望根據 繪制面積圖type,即對于日期,如果type=1, 2, 3,我將使用顏色gray,lightpink并skyblue分別使用。
我怎么能那樣做?謝謝。
預期的情節將是這樣的:

參考代碼:
year_n_1 = [1.5, 3, 10, 13, 22, 36, 30, 33, 24.5, 15, 6.5, 1.2]
year_n = [2, 7, 14, 17, 20, 27, 30, 38, 25, 18, 6, 1]
plt.fill_between(np.arange(12), year_n_1, color="lightpink",
alpha=0.5, label='year N-1')
plt.fill_between(np.arange(12), year_n, color="skyblue",
alpha=0.5, label='year N')
plt.legend()
plt.show()
出去:

編輯:
df = df.set_index('date')
colors = ['gray', 'lightpink', 'skyblue']
plt.fill_between(df['value'], color=colors[type], alpha=0.5)
plt.legend()
plt.show()
出去:
TypeError: list indices must be integers or slices, not type
uj5u.com熱心網友回復:
嘗試:
# let's use datetime type
df['date'] = pd.to_datetime(df['date'])
# the colors
colors = ['gray', 'lightpink', 'skyblue']
# loop and plot
fig, ax = plt.subplots()
for i, (t, d) in enumerate(df.groupby('type')):
d.plot.area(x='date', y='value', label=t, ax=ax, alpha=0.5, color=colors[i])
plt.show()
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/357852.html
標籤:蟒蛇-3.x matplotlib
