2017-04-14 98 views
1

我想在同一个图上绘制一条线和一条线。这是什么工作,什么不工作。有人会解释为什么吗?熊猫在线的阴谋条形图

什么行不通:

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) 

enter image description here

但不知何故,当我在第一个情节删除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) 

enter image description here

+0

的可能的复制[熊猫情节不覆盖(http://stackoverflow.com/questions/42948576/pandas-plot-does-not-overlay) – ImportanceOfBeingErnest

+0

[这个问题](HTTP:/ /stackoverflow.com/questions/42813890/python-making-combined-bar-and-line-plot-with-secondary-y-axis)也可能是有趣的。 – ImportanceOfBeingErnest

回答

4

的主要问题那是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) 

治疗一年这样有道理的,因为你把今年作为一个明确的数据,无论如何,和按字母顺序排列的数字顺序相匹配。

enter image description here

+0

非常丰富! – piRSquared

+0

这是一个很好的伎俩! – MaxU

+0

我有一种感觉,我只有在幸运运动中才有所作为,这就是为什么我发布了这个问题。解释清楚,解决方案解决了我的任务中涉及的几个相关问题。谢谢! – Crystie