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

如何在Matplotlib单个图例项中组合两种带中心黑点的方块标记?

实现并排带中心黑点的双方块图例

直接借助matplotlib.legend_handler.HandlerTuple就能搞定,之前失败大概率是嵌套逻辑或参数设置问题。以下是最简实现代码:

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple

# 模拟数据
x = [1,2,3]
y_a = [1,2,3]
y_b = [2,3,4]
y_special = [3,4,5]

fig, ax = plt.subplots()

# 绘制基础标记
line_a, = ax.plot(x, y_a, marker='s', color='white', markeredgecolor='black', linestyle='None', label='A')
line_b, = ax.plot(x, y_b, marker='s', color='gray', markeredgecolor='black', linestyle='None', label='B')
# 特殊数据的实际绘制(仅保留原样式,重点修改图例)
ax.plot(x, y_special, marker='o', color='black', linestyle='None')

# 构建带中心黑点的方块组合
# 白方块+中心黑点
white_sq = plt.Line2D([], [], marker='s', color='white', markeredgecolor='black', linestyle='None')
black_dot_white = plt.Line2D([], [], marker='o', color='black', markersize=4, linestyle='None')
# 灰方块+中心黑点
gray_sq = plt.Line2D([], [], marker='s', color='gray', markeredgecolor='black', linestyle='None')
black_dot_gray = plt.Line2D([], [], marker='o', color='black', markersize=4, linestyle='None')

# 嵌套元组:先叠加方块与黑点,再将两个组合打包实现并排
special_legend_item = ((white_sq, black_dot_white), (gray_sq, black_dot_gray))

# 更新图例手柄与标签
handles, labels = ax.get_legend_handles_labels()
# 替换原第三个图例项
handles[2] = special_legend_item
labels[2] = 'special data'

# 用HandlerTuple处理嵌套元组,ndivide=None确保标记按预期并排
ax.legend(handles=handles, labels=labels,
          handler_map={tuple: HandlerTuple(ndivide=None)})

plt.show()

关键说明

  • 每个带中心黑点的方块由方块标记和小黑点标记组成元组,HandlerTuple会自动叠加两者
  • 将两个带点方块的元组再次打包,即可实现并排展示
  • ndivide=None是核心参数,避免HandlerTuple拆分内部嵌套元组,保证标记排列符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:38:07