将图例添加到在同一轴上具有多个图的matplotlib箱图中 [英] Adding a legend to a matplotlib boxplot with multiple plots on same axes
问题描述
我有一个用matplotlib生成的箱线图:
但是,我不知道如何生成图例.每当我尝试以下操作时,我都会收到一条错误消息,指出 Legend不支持{boxes:...
这.任何帮助将不胜感激!
bp1 = ax.boxplot(data1,position = [1,4],notch = True,widths = 0.35,patch_artist = True)bp2 = ax.boxplot(data2,position = [2,5],notch = True,widths = 0.35,patch_artist = True)ax.legend([bp1,bp2],['A','B'],loc ='右上')
I have a boxplot generated with 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. 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
result : dict
A dictionary mapping each component of the boxplot to a list of the matplotlib.lines.Line2D instances created. 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.- [...]
Using the boxes
, you can get the legend artists as
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()
这篇关于将图例添加到在同一轴上具有多个图的matplotlib箱图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!