我正在研究時間序列資料集。我想要一個銷售折線圖和一條水平線,顯示一段時間內的平均銷售額。這部分作業正常。
我想在折線圖頂部添加一個條形圖,顯示銷售額何時高于或低于平均銷售額。資料中的每個日期都用布爾 T/F 標記為高于或低于平均值。
當我在我的資料集上執行此操作時,matplotlib 沒有每個日期的條形顏色。
我為這個例子制作了一個玩具套裝,當我在玩具套裝上運行代碼時,它可以正常作業。我已經包含了實際資料、資料型別和不正確的圖表的片段。
我的問題是: 我應該如何排除故障或查看為什么 matplotlib 沒有正確繪制條形圖?
實際資料集

實際資料集型別

實際資料集圖
請注意,根據資料,每周應該是綠色或紅色

實際資料集上的代碼
fig = plt.figure()
ax1 = fig.add_subplot()
x = test['FSCL_WK_BGN_DT']
y = test[['total_sls','avg_sales']]
off_season = test['Off_season']
on_season = test['On_season']
ax1.plot(x,y)
ax2 = ax1.twinx()
ax2.bar(x,on_season, color = 'green')
ax2.bar(x,off_season, color = 'red')
玩具示例
dict_sample = {'date': [1,2,3,4,5],
'sales':[100,200,300,100,200],
'avg_sls': 180,
'over':[False,True,True,False,True],
'under':[True,False,False,True,False]
}
df_sample = pd.DataFrame(dict_sample)
df_sample
圖形玩具示例代碼
ax1 = fig.add_subplot()
x = df_sample['date']
y = df_sample[['sales','avg_sls']]
over = df_sample['over']
under = df_sample['under']
ax1.plot(x,y)
ax2 = ax1.twinx()
ax2.bar(x,over, color = 'green')
ax2.bar(x,under, color = 'red')
代碼輸出 雖然丑陋,但條形是正確的

uj5u.com熱心網友回復:
根據https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html,條形圖的默認寬度為0.8 。當您使用時間序列 x 軸時,這將變為 0.8 秒,有時可能太小而無法顯示任何內容。
嘗試
ax2.bar(x,on_season, color = 'green', width=86400*0.8)
ax2.bar(x,off_season, color = 'red', width=86400*0.8)
玩具示例使用不同的整數標度,這就是為什么它作業得如此出色。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/397679.html
標籤:Python 熊猫 matplotlib
