You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在箱线图中为绘制的自定义线条添加图例?

解决Matplotlib箱线图自定义线条无法添加图例的问题

你的问题出在axes.plot()的返回值上——这个函数返回的是包含单个Line2D对象的列表,而非单个对象,直接把line传入legend()会导致无法识别;同时你也未给自定义线条补充对应的图例标签。

修改方案

  1. 取line列表中的第一个元素(即实际的线条对象)传入图例
  2. 在图例标签列表中补充自定义线条的标签

修改后的完整代码

import matplotlib.pyplot as plt
import numpy as np


def box_plot():
    data = np.array([
        [17.7, 22.9, 17.6],     #M4 Ratio 17
        [17.3, 22.0, 16.4],     #M5 Ratio 13
        [15.8, 21.4, 16.0],     #M6 Ratio 10
        [16.1, 21.8, 17.6]      #M7 Ratio 8.8
    ])
    
    labels = ['AS', 'JB', 'EG']
    
    meanlineprops = dict(linestyle='solid', linewidth=1.5, color='black')
    medianprops = dict(linestyle='dashed', linewidth=1.5, color='black')
    
    fig = plt.figure(figsize=(5,5), layout='constrained')
    axes = fig.subplots(ncols=1, nrows=1 )
    bp = axes.boxplot(data, labels=labels, showmeans=True, meanline=True, 
                      meanprops=meanlineprops, medianprops=medianprops)
    axes.set_title('A2')
    axes.grid()
    
    volume_A2 = 18.77
    # plot返回的是列表,用line[0]获取实际线条对象
    line = axes.plot([0,4], [volume_A2, volume_A2], "k--", linewidth=1, 
                     color='black', label='True volume')
    axes.set_xlim(0.5, 3.5)
    
    axes.set_ylabel('Volume (ml)')
    axes.set_xlabel('Medical Physicist')
    
    # 修正:取line[0],并补充第三个标签
    axes.legend([ bp['means'][0], bp['medians'][0], line[0]], 
                ['Mean', 'Median', 'True volume'])
    
    plt.show()  # 添加显示图像的语句

box_plot()

更简洁的写法(可选)

你也可以让Matplotlib自动收集所有带label参数的元素生成图例,只需要给均值和中位数手动设置标签,再直接调用legend()即可:

# 绘制箱线图后添加:
bp['means'][0].set_label('Mean')
bp['medians'][0].set_label('Median')

# 直接调用legend,无需手动传参
axes.legend()

内容的提问来源于stack exchange,提问作者lolloa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 21:23:21