简体   繁体   English

熊猫在线条上绘制条形图

[英]Pandas plot bar chart over line

I'm trying to plot a bar and a line on the same graph.我试图在同一张图上绘制一条条和一条线。 Here is what works and what does not work.这是有效的和无效的。 Would anyone please explain why?有没有人请解释一下为什么?

What does NOT work:什么不起作用:

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)

在此处输入图片说明

But somehow it works when I delete the x=['year'] in the first plot:但是当我删除第一个图中的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)

在此处输入图片说明

The main issue is that kinds="bar" plots the bars on the low end of the x-axis, (so 2001 is actually on 0) while kind="line" plots it according to the value given.主要问题是kind="line" kinds="bar"在 x 轴的低端绘制条形图(所以 2001 实际上是 0),而kind="line"根据给定的值绘制它。 Removing the x=["year"] just made it plot the value according to the order (which by luck matches your data precisely).删除x=["year"]只是让它根据顺序绘制值(幸运的是,它与您的数据精确匹配)。

There might be a better way, but the quickest way I know would be to stop considering the year to be a number.可能有更好的方法,但我所知道的最快方法是停止将年份视为一个数字。

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)

Treating the year this way makes sense since you treat the year as a categorical data anyway, and the alphabetic order matches the numerical order.以这种方式处理年份是有道理的,因为无论如何您都将年份视为分类数据,并且字母顺序与数字顺序相匹配。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM