Matplotlib柱状图中的两个图例

4
我的问题与 matplotlib两个图例超出绘图范围 非常相似。有一个答案适用于普通线图。
我在复制解决方案时遇到了条形图的问题...
问题是,在给定的解决方案中,l1l2等是<matplotlib.lines.Line2D,如果我对bar-plot采用同样的技巧,它无法推断颜色...

enter image description here

代码:

import matplotlib.pyplot as plt
import numpy as np

bar_data_cost = np.random.rand(4,11)
bar_data_yield =  np.random.rand(4,11)
cmap_yield = plt.cm.Greens(np.linspace(0.2, 1, len(bar_data_cost)))
cmap_costs = plt.cm.Oranges(np.linspace(0.2, 1, len(bar_data_cost)))

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(20,8))

ax1 = axes
y_offset_yield = np.zeros(len(bar_data_yield[0]))
y_offset_cost = np.zeros(len(bar_data_cost[0]))
index1 = np.arange(len(bar_data_yield[1])) - 0.2
index2 = np.arange(len(bar_data_yield[1])) + 0.2

for row in range(len(bar_data_yield)):
    b1 = ax1.bar(left=index1, width=0.4, height=bar_data_yield[row], bottom=y_offset_yield, color=cmap_yield[row])
    y_offset_yield = bar_data_yield[row]

for row in range(len(bar_data_yield)):
    b2 = ax1.bar(left=index2, width=0.4, height=bar_data_cost[row], bottom=y_offset_cost, color=cmap_costs[row])
    y_offset_cost = bar_data_cost[row]


fig.legend(b1, grouped_dataset.index.levels[0], fontsize=16, loc="upper right")
fig.legend(b2, grouped_dataset.index.levels[0], fontsize=16, loc="center right")

@Parfait 已修复! - Ladenkov Vladislav
但是没有定义grouped_dataset。但我找到了你的问题!现在回答... - Parfait
1个回答

4

目前,您的图例仅输出了for循环中的最后一个b1b2,因为它们在每次迭代中被重新赋值。在发布的链接中,元组行作为legend的第一个参数传递。因此,在迭代添加条形图之后,将b1列表和b2列表传递到legend调用中。

以下示例使用种子数据进行再现,并将您的grouped_dataset.index.levels [0]替换为此在您的帖子中未知。

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(82018)

...

b1_list = []
for row in range(len(bar_data_yield)):
    index1 = np.arange(len(bar_data_yield[row])) - 0.2
    b1_list.append(ax1.bar(left=index1, width=0.4, height=bar_data_yield[row], 
                           bottom=y_offset_yield, color=cmap_yield[row]))
    y_offset_yield = bar_data_yield[row]

b2_list = []
for row in range(len(bar_data_yield)):
    index2 = np.arange(len(bar_data_yield[row])) + 0.2
    b2_list.append(ax1.bar(left=index2, width=0.4, height=bar_data_cost[row], 
                           bottom=y_offset_cost, color=cmap_costs[row]))
    y_offset_cost = bar_data_cost[row]

fig.legend(b1_list, list('ABCD'), fontsize=16, loc="upper right")
fig.legend(b2_list, list('WXYZ'), fontsize=16, loc="center right")

plt.show()
plt.clf()
plt.close()

Plot Output


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接