[英]Pandas plot bar chart over line
我試圖在同一張圖上繪制一條條和一條線。 這是有效的和無效的。 有沒有人請解釋一下為什么?
什么不起作用:
df = pd.DataFrame({'year':[2001,2002,2003,2004,2005], 'value':[100,200,300,400,500]})
df['value1']= df['value']*0.4
df['value2'] = df['value']*0.6
fig, ax = plt.subplots(figsize = (15,8))
df.plot(x = ['year'], y = ['value'], kind = 'line', ax = ax)
df.plot(x = ['year'], y= ['value1','value2'], kind = 'bar', ax = ax)
但是當我刪除第一個圖中的x=['year']
時,它以某種方式起作用:
fig, ax = plt.subplots(figsize = (15,8))
df.plot(y = ['value'], kind = 'line', ax = ax)
df.plot(x = ['year'], y= ['value1','value2'], kind = 'bar', ax = ax)
主要問題是kind="line"
kinds="bar"
在 x 軸的低端繪制條形圖(所以 2001 實際上是 0),而kind="line"
根據給定的值繪制它。 刪除x=["year"]
只是讓它根據順序繪制值(幸運的是,它與您的數據精確匹配)。
可能有更好的方法,但我所知道的最快方法是停止將年份視為一個數字。
df = pd.DataFrame({'year':[2001,2002,2003,2004,2005], 'value':[100,200,300,400,500]})
df['value1']= df['value']*0.4
df['value2'] = df['value']*0.6
df['year'] = df['year'].astype("string") # Let them be strings!
fig, ax = plt.subplots(figsize = (15,8))
df.plot(x = ['year'], y = ['value'], kind = 'line', ax = ax)
df.plot(x = ['year'], y= ['value1','value2'], kind = 'bar', ax = ax)
以這種方式處理年份是有道理的,因為無論如何您都將年份視為分類數據,並且字母順序與數字順序相匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.