python - 向 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()
解决方案
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()
推荐阅读
- python - 如何在 matplotlib 中生成密钥
- swift - 可选数组??NSNull() - 表达式太复杂,无法在合理的时间内解决
- python - put_object into s3 boto3 给出了一个损坏的文件
- python - 如何修改 contenteditable 元素的 innerHTML
- python - 无法从scrapy中的html获取电子邮件
- python - 从 Python 3.5 编译 Oracle 包时,Oracle 12c DBA_IDENTIFIERS 未填充
- angular - VS Code:如何在 Angular 模板文件中重构(重命名变量)?
- php - 使用 php 以用户友好的格式获取两个日期的差异
- html - 创建不重新排列的对象行
- python-requests - 主机别名/迷你 DNS?