更改代码以允许超过 3 个堆叠条

Changing code to allow more than 3 stacked bars

所以我在网上找到了这段代码,它绘制了一个包含三个条形图的堆叠条形图(每个条形图都有三个条形图相互堆叠):

%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()

我想让每个堆叠的条形图有 3 个以上的条形图相互堆叠(最好是 8 个),但是当我添加更多的月份时(同时确保三个列表的长度都相等) , 我得到一个

IndexError:list index out of range

并且条形图在图例中仍然只显示三种颜色和三个月。错误指向行:

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

但我不太确定它指的是哪一部分。

解决此问题的最佳方法是什么?

提前致谢!

似乎是一种复杂的方法:

rows = zip(*data)
headers = ['Year', 'Month', 'Value']
colors = ["#006D2C", "#31A354","#74C476"]
df = pd.DataFrame(rows, columns=headers)
(df
 .pivot(index='Year', columns='Month', values='Value')
 .reindex(columns=df.Month.unique())
 .plot.bar(stacked=True, color=colors))

添加月份,例如添加 (2002, 'Apr', 10) 按预期工作(它只是循环颜色):

您还需要添加更多颜色,如果您想要其中的 8 种,请尝试:

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