1

I have a pandas data frame as follows

        batsman      non_striker  partnershipRuns
0      SK Raina       A Flintoff               23
1      SK Raina         DR Smith               90
2      SK Raina     F du Plessis               36
3      SK Raina        JA Morkel               14
10     MS Dhoni    CK Kapugedera               18
11     MS Dhoni         DJ Bravo               51
12     MS Dhoni     F du Plessis               27
13     MS Dhoni        JA Morkel               12
14     MS Dhoni         JDP Oram                6

I am finding it really difficult to create stacked bar plot with either pandas or seaborn. Any help will be appreciated

Tinniam V. Ganesh
  • 1,979
  • 6
  • 26
  • 51

2 Answers2

4

Using Pandas it is very simple to create a plot. Once you have a dataframe simply call plot like in this example (I used your example data set).

import pandas as pd
import matplotlib.pyplot as plt

#create the dataframe from your data
batsman = ['SK Raina','SK Raina','SK Raina','SK Raina','MS Dhoni','MS Dhoni', 'MS Dhoni','MS Dhoni','MS Dhoni']
non_striker = [ 'A Flintoff', 'DR Smith' ,'du Plessis','JA Morkel',  'Kapugedera', 'DJ Bravo', 'du Plessis', 'JA Morkel', 'JDP Oram']
partnershipRuns = [23,90,36,14,18,51,27,12, 6]


df = pd.DataFrame({'batsman': batsman, 'non_striker': non_striker, 'partnershipRuns': partnershipRuns})

#make your data numerical
df = df.pivot(columns='non_striker',index='batsman').fillna(0)
#plot it
df.plot(kind='bar',stacked=True,legend=False)
plt.show()

This yields something like this: Example output

If your data is not numerical, you have to convert it first.

1

I have been able to do it in 2 ways

1)

df1=df.pivot(columns='non_striker',index='batsman').fillna(0)
df1.plot(kind='bar',stacked=True,legend=False)

2)

df1=df.groupby(['batsman','non_striker']).sum().unstack().fillna(0)
df1.plot(kind='bar',stacked=True,legend=False)

Both work. We need to create a table between the columns and then plot after filling NAs with 0senter image description here

Tinniam V. Ganesh
  • 1,979
  • 6
  • 26
  • 51