[英]Matplotlib not plotting all data points in bar graph
我正在研究時間序列數據集。 我想要一個銷售折線圖和一條顯示該時間段內平均銷售額的水平線。 這部分工作正常。
我想在折線圖頂部添加一個條形圖,顯示銷售額何時高於或低於平均銷售額。 使用 boolean 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')
代碼 Output雖然很難看,但條形圖是正確的
根據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)
玩具示例使用不同的 integer 比例尺,這就是它工作得如此出色的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.