Pandas - Plotting a stacked Bar Chart

PythonMatplotlibPandasIpython NotebookPython 3.4

Python Problem Overview


I am trying to create a stacked bar graph that replicates the picture, all my data is separate from that excel spreadsheet.

enter image description here

I cant figure out how to make a dataframe for it like pictured, nor can I figure out how to make the stacked bar chart. All examples I locate work in different ways to what I'm trying to create.

My dataframe is a csv of all values narrowed down to the following with a pandas dataframe.

      Site Name	   Abuse/NFF
0	 NORTH ACTON	   ABUSE
1	 WASHINGTON	        -
2	 WASHINGTON	       NFF
3	 BELFAST	        -
4	 CROYDON	        - 

I have managed to count the data with totals and get individual counts for each site, I just cant seem to combine it in a way to graph.

Would really appreciate some strong guidance.

Completed code, many thanks for the assistance completing.

test5 = faultdf.groupby(['Site Name', 'Abuse/NFF'])['Site Name'].count().unstack('Abuse/NFF').fillna(0)

test5.plot(kind='bar', stacked=True)

Python Solutions


Solution 1 - Python

Are you getting errors, or just not sure where to start?

%pylab inline
import pandas as pd
import matplotlib.pyplot as plt

df2 = df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF').fillna(0)
df2[['abuse','nff']].plot(kind='bar', stacked=True)

stacked bar plot

Solution 2 - Python

That should help

df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)

Solution 3 - Python

Maybe you can use pandas crosstab function

test5 = pd.crosstab(index=faultdf['Site Name'], columns=faultdf['Abuse/NFF'])

test5.plot(kind='bar', stacked=True)

Solution 4 - Python

If you want to change the size of plot the use arg figsize

df.groupby(['NFF', 'ABUSE']).size().unstack()
      .plot(kind='bar', stacked=True, figsize=(15, 5))

Solution 5 - Python

from matplotlib import cm
cmap = cm.get_cmap('Spectral') # Colour map (there are many others)

df.plot(kind='bar', stacked=True, figsize=(20, 10), cmap=cmap, edgecolor='None')
plt.show()

This will also avoid duplicate colors in the legend of your bar chart.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKuzenView Question on Stackoverflow
Solution 1 - PythonchucklukowskiView Answer on Stackoverflow
Solution 2 - PythonKyofaView Answer on Stackoverflow
Solution 3 - PythonRafael Jose Gonzlez de GouveiaView Answer on Stackoverflow
Solution 4 - Pythonkamran kausarView Answer on Stackoverflow
Solution 5 - PythonToeyView Answer on Stackoverflow