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

Matplotlib如何实现同时标注线型与颜色的双维度表格形式图例

实现方案

该需求完全可以实现,核心思路是结合 Matplotlib 的表格组件 + 自定义线条示例元素,模拟双维度标识的图例效果。

完整可运行代码

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

# 原有绘图逻辑
mul_list = [1,2,3]
add_list = [[1,2,3],[4,5,6]]
linestyles = [':','--','-']
linecolors = ['r','g']
time = np.linspace(0,5)

fig, ax = plt.subplots(figsize=(8, 5))
for i,mul in enumerate(mul_list):
    for j,add in enumerate(add_list):
        ax.plot(time, mul*time + add[i], linestyle=linestyles[i], color=linecolors[j])

# -------------------------- 表格图例实现 --------------------------
# 表格结构:4行3列,和预期图例结构完全对应
table_data = [
    ["", "r", "g"],  # 表头行
    [":  m = 1", "a = 1", "a = 4"],
    ["--  m = 2", "a = 2", "a = 5"],
    ["-  m = 3", "a = 3", "a = 6"]
]

# 创建表格,放在坐标轴右侧避免遮挡绘图区域
table = ax.table(
    cellText=table_data,
    loc='right',
    cellLoc='left',
    bbox=[1.1, 0, 0.4, 1]  # 位置参数:[左边界, 下边界, 宽度, 高度],相对于坐标轴坐标系
)

# 统一调整表格样式
table.auto_set_font_size(False)
table.set_fontsize(10)
for (row, col), cell in table.get_celld().items():
    cell.set_height(0.2)
    cell.set_width(0.15)

# 为表头添加颜色标识(第一行第2、3列)
for j, color in enumerate(linecolors):
    cell = table.get_celld()[(0, j+1)]
    # 添加对应颜色的线条示例
    line = Line2D([0.1, 0.3], [0.5, 0.5], color=color, linewidth=2, transform=cell.get_transform())
    cell.add_artist(line)
    # 文本右移避免和线条重叠
    cell.get_text().set_x(0.4)

# 为行头添加线型标识(第1-3行第1列)
for i, ls in enumerate(linestyles):
    cell = table.get_celld()[(i+1, 0)]
    # 添加对应样式的黑色线条示例
    line = Line2D([0.1, 0.3], [0.5, 0.5], color='k', linestyle=ls, linewidth=2, transform=cell.get_transform())
    cell.add_artist(line)
    cell.get_text().set_x(0.4)

# 为数据单元格添加对应参数的完整线条示例(和图中实际曲线样式完全匹配)
for i, ls in enumerate(linestyles):
    for j, color in enumerate(linecolors):
        cell = table.get_celld()[(i+1, j+1)]
        line = Line2D([0.1, 0.3], [0.5, 0.5], color=color, linestyle=ls, linewidth=2, transform=cell.get_transform())
        cell.add_artist(line)
        cell.get_text().set_x(0.4)

# 调整画布边距避免表格被截断
plt.subplots_adjust(right=0.75)
plt.show()

核心逻辑说明

  • 先完成原有曲线绘制逻辑
  • 构造和预期图例结构匹配的表格文本数据,通过ax.table创建表格放在坐标轴右侧
  • 遍历表格单元格,为需要显示标识的位置添加自定义Line2D元素,分别对应颜色标识、线型标识、完整曲线样式标识
  • 调整文本位置和表格参数避免元素重叠,运行后即可得到符合要求的双维度表格图例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:48:03