简体   繁体   English

将图例添加到在同一轴上具有多个图的 matplotlib 箱线图

[英]Adding a legend to a matplotlib boxplot with multiple plots on same axes

I have a boxplot generated with matplotlib:我有一个用 matplotlib 生成的箱线图:

在此处输入图片说明

However, I have no idea how to generate the legend.但是,我不知道如何生成图例。 Whenever I try the following I get an error saying Legend does not support {boxes: ... I've done a fair bit of searching and there doesn't seem to be an example showing how to achieve this.每当我尝试以下操作时,我都会收到一条错误消息,指出Legend does not support {boxes: ...我已经进行了大量搜索,但似乎没有示例说明如何实现这一点。 Any help would be appreciated!任何帮助,将不胜感激!

bp1 = ax.boxplot(data1, positions=[1,4], notch=True, widths=0.35, patch_artist=True)
bp2 = ax.boxplot(data2, positions=[2,5], notch=True, widths=0.35, patch_artist=True)

ax.legend([bp1, bp2], ['A', 'B'], loc='upper right')

The boxplot returns a dictionary of artists boxplot返回艺术家字典

result : dict结果:字典
A dictionary mapping each component of the boxplot to a list of the matplotlib.lines.Line2D instances created.将箱线图的每个组件映射到创建的 matplotlib.lines.Line2D 实例列表的字典。 That dictionary has the following keys (assuming vertical boxplots):该字典具有以下键(假设为垂直箱线图):

  • boxes : the main body of the boxplot showing the quartiles and the median's confidence intervals if enabled. boxes :箱线图的主体,显示四分位数和中位数的置信区间(如果启用)。
  • [...] [...]

Using the boxes , you can get the legend artists as使用这些boxes ,您可以将传奇艺术家作为

ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ['A', 'B'], loc='upper right')

Complete example:完整示例:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

data1=np.random.randn(40,2)
data2=np.random.randn(30,2)

fig, ax = plt.subplots()
bp1 = ax.boxplot(data1, positions=[1,4], notch=True, widths=0.35, 
                 patch_artist=True, boxprops=dict(facecolor="C0"))
bp2 = ax.boxplot(data2, positions=[2,5], notch=True, widths=0.35, 
                 patch_artist=True, boxprops=dict(facecolor="C2"))

ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ['A', 'B'], loc='upper right')

ax.set_xlim(0,6)
plt.show()

在此处输入图片说明

Just as a complement to @ImportanceOfBeingErnest's response, if you are plotting in a for loop like this:作为对@ImportanceOfBeingErnest 响应的补充,如果您在这样的 for 循环中绘图:

for data in datas:
    ax.boxplot(data, positions=[1,4], notch=True, widths=0.35, 
             patch_artist=True, boxprops=dict(facecolor="C0"))

You cannot save the plots as variables.您不能将图保存为变量。 So in that case, create legend labels list legends , append the plots into another list elements and use list comprehension to put a legend for each of them:因此,在这种情况下,创建图例标签列表legends ,将图附加到另一个列表elements并使用列表理解为每个elements放置一个图例:

labels = ['A', 'B']
colors = ['blue', 'red']
elements = []

for dIdx, data in enumerate(datas):
    elements.append(ax.boxplot(data, positions=[1,4], notch=True,\
    widths=0.35, patch_artist=True, boxprops=dict(facecolor=colors[dIdx])))

ax.legend([element["boxes"][0] for element in elements], 
    [labels[idx] for idx,_ in enumerate(datas)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM