我试图通过列表理解生成堆叠的条形图,而不是创建十几行单独创建的ax.bar代码;然而,我下面的过程没有绘制任何内容。
以下是MWE:
stacked_bar = [0.03, 0.03, 0.14]
color_dict = {'cat1': '#8661C5',
'cat2': '#0078D4',
'cat3': '#2F2F2F'}
bar_position=0
stacked_bar_generator = [
ax1.bar(bar_position,
np.sum(stacked_bar[:value+1]),
color=key[1], # color hex
bottom=0, # bottom is 0
width=0.25)
for (key, value) in
zip(color_dict.items(), range(len(stacked_bar)))
]
fig = plt.figure(figsize=(8, 6), dpi=60)
ax1 = fig.add_subplot(1, 1, 1)
stacked_bar_generator
fig.canvas.draw()发布于 2021-08-05 15:02:42
以下是多个条形图的示例
import matplotlib.pyplot as plt
import numpy as np
stacked_bar = np.array([[0.03, 0.03, 0.14], [0.07, 0.04, 0.08]]).T
colors = ['#8661C5', '#0078D4', '#2F2F2F']
n_categories, n_labels = stacked_bar.shape
labels = range(n_labels)
categories = range(n_categories)
fig, ax = plt.subplots(figsize=(8, 6), dpi=60)
for c in range(n_categories):
values = stacked_bar[c]
color = colors[c]
ax.bar(labels,
values,
color=color,
bottom=np.sum(stacked_bar[:c, :], axis=0),
width=0.25)
plt.show()失败的原因是因为您没有更新每个条形图的最低值(应该设置为先前值的总和)。
我真的认为简单的for循环在这里更合适,因为您的目标不是构建某种特殊类型的列表,而是迭代类别并绘制条形图。列表理解只会让这看起来过于混乱。
https://stackoverflow.com/questions/68668388
复制相似问题