[英]Adding a legend to a matplotlib boxplot with multiple plots on same axes
我有一個用 matplotlib 生成的箱線圖:
但是,我不知道如何生成圖例。 每當我嘗試以下操作時,我都會收到一條錯誤消息,指出Legend does not support {boxes: ...
我已經進行了大量搜索,但似乎沒有示例說明如何實現這一點。 任何幫助,將不勝感激!
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')
boxplot
返回藝術家字典
結果:字典
將箱線圖的每個組件映射到創建的 matplotlib.lines.Line2D 實例列表的字典。 該字典具有以下鍵(假設為垂直箱線圖):
boxes
:箱線圖的主體,顯示四分位數和中位數的置信區間(如果啟用)。- [...]
使用這些boxes
,您可以將傳奇藝術家作為
ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ['A', 'B'], loc='upper right')
完整示例:
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()
作為對@ImportanceOfBeingErnest 響應的補充,如果您在這樣的 for 循環中繪圖:
for data in datas:
ax.boxplot(data, positions=[1,4], notch=True, widths=0.35,
patch_artist=True, boxprops=dict(facecolor="C0"))
您不能將圖保存為變量。 因此,在這種情況下,創建圖例標簽列表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.