pandas 绘制线条上方的条形图 [英] Pandas plot bar chart over line

查看:48
本文介绍了 pandas 绘制线条上方的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在同一个图形上绘制一条条和一条线.这是行之有效的,而行不通的.谁能解释一下为什么?

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?

什么不起作用:

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'] 时,它以某种方式起作用:

But somehow it works when I delete the x=['year'] in the first plot:

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)

推荐答案

主要问题是 kinds="bar" 在 x 轴的低端绘制条形图,(所以 2001实际上是 0) 而 kind="line" 根据给定的值绘制它.删除 x = ["year"] 只是使其按照顺序绘制值(幸运的是,它与您的数据精确匹配).

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. Removing the x=["year"] just made it plot the value according to the order (which by luck matches your data precisely).

可能有更好的方法,但我所知道的最快方法是停止将年份视为一个数字.

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.

这篇关于 pandas 绘制线条上方的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆