【发布时间】: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