Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

python - 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)

enter image description here

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)

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...