How to plot DataFrame as stacked bar chart after grouping

I am using a dataframe DF

And below is how I select from my data frame :

CountryList= DF[(DF['Sector'] == 'Test')].groupby(DF['Country'])['NumberI'].sum()

Which return the following :

    USA                    20
    CHINA                  30
    JAPAN                  10

Fact is that I don’t understand How to plot a single bar with in it : 3 Color (1 for USA 1 for CHINA and 1 for JAPAN)

enter image description here

>Solution :

You can start as follows. The key here is to specify bottom parameter for function, and to keep track of the current bottom, which is the sum of all previous heights.

I leave to you the process of making this plot beautiful

Also check out a more complex example at the bottom of the web-page, where you can plot multiple such bars on a single plot

import matplotlib.pyplot as plt
import pandas as pd

data = [['usa', 20], ['china', 30], ['japan', 10]]
df = pd.DataFrame(data, columns = ['country', 'some_value'])

current_bottom = 0
for index, row in df.iterrows():[0], row['some_value'], width=1, bottom=current_bottom, label=row['country'])
    current_bottom += row['some_value']

enter image description here

Leave a Reply