我试图将matplotlib.org上给出的示例概括为堆积条形图。
labels = ('G1','G2','G3','G4','G5');
values = [(20,35,30,35,27),(25,32,34,20,25),(3,4,5,6,7)];
for i in range(len(values)):
if i == 0:
plt.bar(np.arange(len(labels)),values[i],1);
else:
plt.bar(np.arange(len(labels)),values[i],1,bottom=values[i-1]);
plt.xticks(np.arange(len(labels))+0.5,labels);
但是现在我遇到了问题,这些条似乎没有正确堆叠:
如果您想运行代码import numpy as np
,import matplotlib.pyplot as plt
和plt.show()
。
如果您愿意,还可以建议如何为每个酒吧获得不同的颜色。
答案 0 :(得分:1)
这样的事情:
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
from six.moves import zip
def stack_bar(ax, list_of_vals, color_cyle=None, **kwargs):
"""
Generalized stacked bar graph.
kwargs are passed through to the call to `bar`
Parameters
----------
ax : matplotlib.axes.Axes
The axes to plot to
list_of_vals : iterable
An iterable of values to plot
color_cycle : iterable, optional
color_cycle is None, defaults
to `cycle(['r', 'g', 'b', 'k'])`
"""
if color_cyle is None:
color_cyle = cycle(['r', 'g', 'b', 'k'])
else:
color_cycle = cycle(color_cycle)
v0 = len(list_of_vals[0])
if any(v0 != len(v) for v in list_of_vals[1:]):
raise ValueError("All inputs must be the same length")
edges = np.arange(v0)
bottom = np.zeros(v0)
for v, c in zip(list_of_vals, color_cyle):
ax.bar(edges, v, bottom=bottom, color=c, **kwargs)
bottom += np.asarray(v)
fig, ax = plt.subplots(1, 1)
values = [(20,35,30,35,27),(25,32,34,20,25),(3,4,5,6,7)]
stack_bar(ax, values, width=1)
它需要一些钟声和口哨以及错误检查
也是gist
答案 1 :(得分:1)
对bottom
的使用存在误解。工作代码现在是:
for i in range(len(values)):
plt.bar(np.arange(len(labels)),values[i],1,bottom=[sum([values[j][pos] for j in range(i)]) for pos in range(len(labels))]);
plt.xticks(np.arange(len(labels))+0.5,labels);
对于一个易于打印的区别,我现在将使用颜色kwarg:
color=str(1.0/(len(values)-i))