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

如何使用Python的Matplotlib绘制包含字符串的助记符图

用Matplotlib绘制带文本的类六边形图形

实现思路

Matplotlib没有原生的六边形文本框组件,但可以通过patches.RegularPolygon绘制六边形轮廓,再配合text函数将文本居中放置在图形内,同时兼容单个字符串或字符串列表的输入,支持多六边形的蜂窝状排列。

完整代码示例

import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon

def draw_hex_labels(labels, figsize=(10, 6), hex_radius=0.5, spacing=1.2):
    fig, ax = plt.subplots(figsize=figsize)
    ax.set_aspect('equal')
    ax.axis('off')

    # 统一处理输入:单个字符串转列表
    if isinstance(labels, str):
        labels = [labels]

    # 计算蜂窝状排列的坐标
    x_coords, y_coords = [], []
    row, col = 0, 0
    for idx, _ in enumerate(labels):
        x = col * spacing * hex_radius * 1.5
        y = row * spacing * hex_radius * (3**0.5)
        # 偶数行偏移半个间距,模拟蜂窝布局
        if row % 2 == 1:
            x += spacing * hex_radius * 0.75
        x_coords.append(x)
        y_coords.append(y)
        col += 1
        # 每6个六边形换一行(可按需调整)
        if (idx + 1) % 6 == 0:
            row += 1
            col = 0

    # 绘制六边形与文本
    for x, y, label in zip(x_coords, y_coords, labels):
        # 绘制六边形
        hex_patch = RegularPolygon((x, y), numVertices=6, radius=hex_radius,
                                   edgecolor='black', facecolor='#e6f3ff')
        ax.add_patch(hex_patch)
        # 居中添加文本
        ax.text(x, y, label, ha='center', va='center', fontsize=12)

    # 调整视图范围,确保所有图形可见
    ax.set_xlim(min(x_coords) - hex_radius, max(x_coords) + hex_radius)
    ax.set_ylim(min(y_coords) - hex_radius, max(y_coords) + hex_radius)
    plt.tight_layout()
    plt.show()

# 测试单个字符串
draw_hex_labels("state1")

# 测试字符串列表
draw_hex_labels(["state1", "state2", "state3", "CPU_LOAD", "FSM_IDLE", "FSM_EXEC"])

关键细节说明

  • 六边形绘制:RegularPolygon的numVertices=6指定为六边形,radius控制图形大小,可通过edgecolor和facecolor自定义边框与填充色。
  • 文本对齐:用ha='center'和va='center'确保文本在六边形内居中。
  • 布局适配:蜂窝状排列更贴近数字仿真场景的常见布局,可修改每行六边形数量(代码中为6个)调整密度。
  • 输入兼容:自动判断输入类型,将单个字符串转为列表,统一处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:12:16