首页 > 解决方案 > 向 seaborn 箱线图添加自定义图例

问题描述

我使用 seaborn 生成了 M 种方法的 N 个箱线图,然后我用相同的颜色为每种方法的箱线图上色。我现在只想添加一个图例,以不同的颜色显示 M 方法的名称(例如 red_line 方法 A、blue_line 方法 B 等)。有什么快速的方法吗?

bplot = sns.boxplot(data=[d for d in data])   
colors = ["red", "green", "blue"]    
color_counter = 0
for i in range(len(data)-len(c)): 
    mybox = bplot.artists[i]
    mybox.set_facecolor(colors[color_counter])
    color_counter = color_counter + 1
    if color_counter == len(methods): 
        color_counter=0   
# COMMENTING NEXT CODE BLOCK AS IT OUTPUTS TEXT ASSOCIATED TO GRAY LINES (I want them to be colored instead) 
# leg = plt.legend(labels=[method for method in methods])
# for legobj in leg.legendHandles:
#     legobj.set_linewidth(12.0)
# params = {'legend.fontsize': 80}
# plt.rcParams.update(params)
plt.legend()  
plt.title('Title')
plt.show()

标签: pythonmatplotlibseabornboxplot

解决方案


Matplotlib 允许您创建自定义图例,其中几乎包含您想要的任何内容。

https://matplotlib.org/3.2.1/gallery/text_labels_and_annotations/custom_legends.html

对于您的情况,您将创建类似

from matplotlib.lines import Line2D
import matplotlib.pyplot as plt

legend_elements = [Line2D([0], [0], color='red', lw=4, label='Method 1'),
Line2D([0], [0], color='green', lw=4, label='Method 2'),
Line2D([0], [0], color='blue', lw=4, label='Method 3')]

# Create the figure
fig, ax = plt.subplots()
ax.legend(handles=legend_elements, loc='center')

plt.show()


推荐阅读