Python:广义Pyplot堆叠条
我已经尝试将上面给出的示例推广到堆叠条形图 但现在我遇到了一个问题,这些条似乎没有正确堆叠: 如果要运行代码,Python:广义Pyplot堆叠条,python,numpy,matplotlib,plot,stacked,Python,Numpy,Matplotlib,Plot,Stacked,我已经尝试将上面给出的示例推广到堆叠条形图 但现在我遇到了一个问题,这些条似乎没有正确堆叠: 如果要运行代码,import numpy as np,import matplotlib.pyplot as plt和plt.show() 如果您愿意,您还可以建议如何为每个条获得不同的颜色。类似以下内容: import numpy as np import matplotlib.pyplot as plt from itertools import cycle from six.moves impo
import numpy as np
,import matplotlib.pyplot as plt
和plt.show()
如果您愿意,您还可以建议如何为每个条获得不同的颜色。类似以下内容:
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)
它需要一些提示和错误检查
另外,作为一个,人们对
底部的使用存在误解。工作代码现在是:
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))
color=str(1.0/(len(values)-i))