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
345 views
in Technique[技术] by (71.8m points)

pandas - Matplotlib plot bar chart with 2 columns relationship in dataframes

I have been stuck at plotting dataframe. This might be simple, but I can't able to figure out!

I have panda dataframe records like this:

    Year  occurrence   Count
0   2011           0     306
1   2011           1    1838
2   2012           0     422
3   2012           1    1816
4   2013           0     423
5   2013           1    3471
6   2014           0     537
7   2014           1    3239
8   2015           0     993
9   2015           1    7668
10  2016           0     415
11  2016           1    2052
12  2017           0     511
13  2017           1    4750
14  2018           0     705
15  2018           1    2125

I want to plot this dataframe as bar chart such that, x-axis contains Year and Y-axis contains Count.

  1. Now I want to plot this Count based on occurrence value. means that in year 2011 one bar has count=306 and second bar has count=1838, same for remaining years.
  2. Also, if possible, I also have to display stacked bar chart based on same thing.
  3. And, How can I plot line charts with two lines in it?

    Can anyone have workaround on this?

    I have created sample df based on my result:
df = spark.createDataFrame({
(2011,  0,   306),
(2011,  1,  1838),
(2012,  0,   422),
(2012,  1,  1816),
(2013,  0,   423),
(2013,  1,  3471),
(2014,  0,   537),
(2014,  1,  3239),
(2015,  0,   993),
(2015,  1,  7668),
(2016,  0,   415),
(2016,  1,  2052),
(2017,  0,   511),
(2017,  1,  4750),
(2018,  0,   705),
(2018,  1,  2125),
}, ['Year', 'occurrence', 'Count'])

pdf_1 = df.toPandas()

I have tried with this:
pdf_1.plot(x='Year', y=['Count'], kind='bar')

but it does not give me what exactly I wanted.

question from:https://stackoverflow.com/questions/65846166/matplotlib-plot-bar-chart-with-2-columns-relationship-in-dataframes

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

1 Reply

0 votes
by (71.8m points)

You can use pivot to reshape:

pdf_1.pivot('Year', 'occurrence', 'Count').plot.bar(stacked=True)

Output:

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

...