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

Python中为置信区间对自定义图例标签的实现方法

自定义置信区间图例(按测量项标注)

可以通过手动创建图例元素实现需求,核心思路是给每个测量项的上下边界和填充区域使用同一颜色,再基于这些颜色创建独立的图例条目,替换默认生成的上下边界图例。

修改后的完整代码

import pandas as pd
from matplotlib.pyplot import cm
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Patch

# 定义测量项数据
item1 = pd.DataFrame([10,15,12], index=['2018-01-01', '2018-01-02', '2018-01-03'])
item2 = pd.DataFrame([16,18,20], index=['2018-01-01', '2018-01-02', '2018-01-03'])
item3 = pd.DataFrame([14,18,17], index=['2018-01-01', '2018-01-02', '2018-01-03'])
dfs = [item1, item2, item3]
item_labels = ['item1', 'item2', 'item3']  # 每个测量项的标签

def compute(df):
    lower = df[0] - 1
    upper = df[0] + 1
    result = pd.DataFrame({'lower': lower, 'upper': upper}, index=df.index)
    return result

def run_function():
    color = iter(cm.rainbow(np.linspace(0, 1, len(dfs))))
    legend_elements = []  # 存储自定义图例元素
    
    for i in range(len(dfs)):
        current_color = next(color)
        thing = compute(dfs[i])
        
        # 绘制上下边界,隐藏默认标签(避免生成重复图例项)
        if i == 0:
            ax = thing.plot(color=current_color, label='_nolegend_')
        else:
            thing.plot(ax=ax, color=current_color, label='_nolegend_')
        
        # 绘制填充区域,用同一颜色并添加透明度
        plt.fill_between(thing.index, thing["upper"], thing["lower"], color=current_color, alpha=0.3)
        
        # 创建当前测量项的图例元素(用填充色块代表)
        legend_elements.append(Patch(facecolor=current_color, alpha=0.3, label=item_labels[i]))
    
    # 添加自定义图例
    plt.legend(handles=legend_elements)
    plt.ylim(0,25)
    plt.show()

run_function()

关键修改说明

  • 统一颜色:每个测量项的上下边界和填充区域使用同一颜色,填充区域添加alpha参数让阴影更柔和。
  • 隐藏默认图例项:调用plot时设置label='_nolegend_',避免Matplotlib自动为lower和upper列生成图例。
  • 创建自定义图例元素:用matplotlib.patches.Patch创建每个测量项对应的色块元素,添加到图例列表中。
  • 替换默认图例:通过plt.legend(handles=legend_elements)手动添加自定义图例,实现按测量项标注的效果。

可选调整

如果想用线条+填充的组合作为图例标识,可以改用Line2D和Patch组合:

from matplotlib.lines import Line2D

# 替换图例元素创建部分
legend_elements.append(
    Line2D([0], [0], color=current_color, lw=2, linestyle='-', label=item_labels[i])
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:57:35