0

Hi am new to python and trying to plot a dataframe.

         subject name  marks
0        maths         ankush    313
1        maths         anvesh    474
2        maths         amruth    264
3      science         ankush     81
4       socail         ankush      4
5        maths         anirudh  16470
6      science         anvesh    568
7       socail         anvesh      5
8      science         amruth     15

enter image description here

am looking to plot the bar graph something like as shown in the figure.

Thank You for your help.

Community
  • 1
  • 1
ankush reddy
  • 481
  • 1
  • 5
  • 28

2 Answers2

2

The problem is two-fold.

  1. What format does data need to be in to produce bar chart?
  2. How to get data into that format?

For the chart you want, you need the names in the x-axis in the index of the dataframe and the subjects as columns.

This requires a pivot

df.set_index(['name', 'subject']).marks.unstack(fill_value=0)

subject  maths  science  socail
name                           
amruth     264       15       0
anirudh   1647        0       0
ankush     313       81       4
anvesh     474      568       5

And the subsequent plot

df.set_index(['name', 'subject']).marks.unstack(fill_value=0).plot.bar()

enter image description here

piRSquared
  • 285,575
  • 57
  • 475
  • 624
0

The above is a very good answer. However since you are new to python, pandas, & matplotlib, I thought I would share a blog post I have found really good in showing the basics of matplotlib and how it is combined with pandas.

http://pbpython.com/effective-matplotlib.html?utm_content=buffer76b10&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer

I hope you find it useful

closlas
  • 136
  • 8