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

Matplotlib绘制双图例:按结构设颜色、按模型设线型

实现Matplotlib双图例(结构-颜色、模型-线型)的DVH曲线绘制

核心需求拆解

  • 不同结构对应固定颜色,不同**模型(Plan)**对应固定线型
  • 生成两个独立图例:一个展示结构与颜色的对应关系,另一个展示模型与线型的对应关系

修改后的完整代码

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

plt.figure(figsize=(12,8))

# 定义线型(对应不同模型)、颜色(对应不同结构)
styles = ['-', '--', ':']  # 补充PS对应的线型
colors = ['blue', 'orange', 'green', 'red', 'purple', 'brown', 'pink', 'grey']

# 补全所有模型
plans = ['Clinical', 'AP', 'PS']

# 循环绘制所有曲线(不设置label,避免图例重复)
for j, plan in enumerate(plans):
    for i, structure in enumerate(structures_dvh):
        if plan == 'Clinical':
            mean_dose, mean_volume = compute_mean_dvh(Lung_R2_adap, structure)
        elif plan == 'AP':
            mean_dose, mean_volume = compute_mean_dvh(Lung_AP, structure)
        elif plan == 'PS':
            mean_dose, mean_volume = compute_mean_dvh(Lung_PS, structure)
        
        # 绘制曲线,仅指定颜色和线型,不设置label
        plt.plot(mean_dose, mean_volume, c=colors[i], ls=styles[j])

# 手动创建结构-颜色的图例手柄
structure_handles = [
    Patch(color=colors[i], label=struct) 
    for i, struct in enumerate(structures_dvh)
]
# 手动创建模型-线型的图例手柄(用黑色统一颜色,突出线型差异)
plan_handles = [
    Line2D([], [], linestyle=styles[j], color='black', label=plan) 
    for j, plan in enumerate(plans)
]

# 添加第一个图例:结构与颜色
plt.legend(handles=structure_handles, loc='lower left', 
           bbox_to_anchor=(0, -0.25), fancybox=True, shadow=True, ncol=4)
# 添加第二个图例:模型与线型
plt.legend(handles=plan_handles, loc='lower right', 
           bbox_to_anchor=(1, -0.25), fancybox=True, shadow=True)

# 图表基础设置
plt.title('Mean DVH')
plt.xlabel('Relative dose')
plt.ylabel('Volume [%]')
plt.grid(True)
plt.tight_layout()

plt.show()

关键修改说明

  1. 补全模型与线型:原代码plans列表缺少PS,同步补充对应线型,确保三个模型都能被绘制
  2. 移除重复label:循环绘图时不设置label,避免自动生成的图例包含重复条目
  3. 自定义图例手柄:
    • 用Patch创建仅展示颜色的结构图例(因为结构只区分颜色)
    • 用Line2D创建仅展示线型的模型图例(统一用黑色,聚焦线型差异)
  4. 双图例布局:通过bbox_to_anchor将两个图例分别放置在图表底部左右两侧,避免重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:13:22