Search code examples
pythonpandasmatplotlibindexingindexoutofboundsexception

Changing code to allow more than 3 stacked bars


So I found this code online which plots a stacked bar chart with three bars (each having three bars stacked on top of one another):

%matplotlib inline

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

matplotlib.style.use('ggplot')


data = [[2000, 2000, 2000, 2001, 2001, 2001, 2002, 2002, 2002],
        ['Jan', 'Feb', 'Mar', 'Jan', 'Feb', 'Mar', 'Jan', 'Feb', 'Mar'],
        [1, 2, 3, 4, 5, 6, 7, 8, 9]]

rows = zip(data[0], data[1], data[2])
headers = ['Year', 'Month', 'Value']
df = pd.DataFrame(rows, columns=headers)

fig, ax = plt.subplots(figsize=(10,7))  

months = df['Month'].drop_duplicates()
margin_bottom = np.zeros(len(df['Year'].drop_duplicates()))
colors = ["#006D2C", "#31A354","#74C476"]

for num, month in enumerate(months):
    values = list(df[df['Month'] == month].loc[:, 'Value'])

    df[df['Month'] == month].plot.bar(x='Year',y='Value', ax=ax, stacked=True, 
                                    bottom = margin_bottom, color=colors[num], label=month)
    margin_bottom += values

plt.show()

I'd like to allow each stacked bar to have more than 3 bars stacked on top of each other (ideally 8), but when I add more months (whilst making sure the three lists are all of equal length), I get an

IndexError:list index out of range

and the bar chart still only shows three colours and three months in the legend. The error points to the line:

df[df['Month'] == month].plot.bar(x='Year',y='Value', ax=ax, stacked=True, 
                                bottom = margin_bottom, color=colors[num], label=month)

but I'm not quite sure which part it is referring to.

What would be the best way of resolving this?

Thanks in advance!


Solution

  • You will need to add more colors as well, if you want 8 of them, try:

    colors = ["#009D2C", "#008D2C","#007D2C","#006D2C", "#005D2C","#004D2C","#003D2C", "#002D2C"]