noiivice
noiivice

Reputation: 400

multiple stacked bar charts on a panel (matplotlib)

my dataframe looks like this:

time Country  Share1 Share2 Share3 Share4
1990  A       10     30     50     10
1991  A       20     70     5      5
1992  A       15     15     50     20
1990  B       40     10     15     35
1991  B       70     10     10     10 

essentially, I would like to create stacked bar charts for each country over time.

a code like:

for values in df.country:
    values.bar(share*, over=year, stacked=True)

...that code won't work, but that's the gist of what I want to do. I want to loop over every country (because I have 200 countries) rather than type them in one by one. Thank you! :-)

Upvotes: 2

Views: 2400

Answers (1)

James
James

Reputation: 36608

This isn't too bad to accomplish once you understand what the plotting methods you can call from a DataFrame object use for the axes and data. The x-axis will be the index of the data frame and each column represents a series (each series has one value per x-value). Assuming your data frame is called df:

# set the values for the x-axis that we want to plot,
# in this case the time values in years
df.set_index(['time'], inplace=True)

# iterate through the list of countries, and create a plot
for country in df.Country.unique():
    # .plot.bar makes bar charts
    ax = df[df.Country==country].plot.bar(stacked=True)
    # make room for the legend, and sets in the upper right corner
    ax.set_xlim(ax.get_xlim()[0],ax.get_xlim()[1]+1)
    ax.legend(loc='upper right')
    # add the country name to the top of the chart.
    ax.set_title(country)

You can save the image file on each iteration.

enter image description here

Upvotes: 2

Related Questions