【问题标题】:Changing code to allow more than 3 stacked bars更改代码以允许超过 3 个堆叠条
【发布时间】:2020-11-07 18:09:21
【问题描述】:

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

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

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

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

提前致谢!

【问题讨论】:

    标签: python pandas matplotlib indexing indexoutofboundsexception


    【解决方案1】:

    看起来很复杂:

    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) 按预期工作(它只是循环颜色):

    【讨论】:

    • 完美,谢谢!如果我想先绘制 2002 条,然后是 2001,然后是 2000,我将如何添加到代码中?
    • 只需在.plot.bar(...)之前的最后一条语句中添加.sort_index(ascending=False)即可。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 2020-03-28
      • 2016-04-07
      • 2017-10-14
      • 2011-07-25
      • 2021-11-04
      相关资源
      最近更新 更多