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

如何用Matplotlib绘制无间隙自定义单元格网格并获取坐标

动态计算坐标绘制带随机边框的单元格网格

要解决这个问题,核心是动态跟踪每个单元格的起始坐标——因为每个单元格的边框和内部尺寸都是随机值,固定间距的网格必然会产生空隙。下面是完整的实现思路和代码:

实现步骤

  • 初始化Matplotlib画布,隐藏无关的坐标轴元素避免干扰
  • 定义随机参数范围:边框宽度1-5,内部白色区域尺寸15-20
  • 用current_x和current_y实时记录下一个单元格的起始绘制坐标
  • 逐个绘制单元格:先计算当前单元格的总宽度/高度,再依次绘制内部白色区域和四个边框,最后更新起始坐标确保无缝衔接

完整代码

import matplotlib.pyplot as plt
import random

# 设置网格行列数
rows = 5
cols = 5

# 初始化画布和坐标轴
fig, ax = plt.subplots(figsize=(10, 10))
# 隐藏坐标轴刻度与边框
ax.set_xticks([])
ax.set_yticks([])
ax.spines[['top', 'right', 'bottom', 'left']].set_visible(False)

# 初始化起始坐标(左下角为起点)
current_x = 0
current_y = 0

for row in range(rows):
    # 每行开始时重置x坐标
    current_x = 0
    for col in range(cols):
        # 生成当前单元格的随机参数
        left_border = random.randint(1, 5)
        right_border = random.randint(1, 5)
        top_border = random.randint(1, 5)
        bottom_border = random.randint(1, 5)
        inner_width = random.randint(15, 20)
        inner_height = random.randint(15, 20)
        
        # 计算单元格总尺寸(边框+内部区域)
        total_width = left_border + inner_width + right_border
        total_height = top_border + inner_height + bottom_border
        
        # 绘制内部白色区域
        ax.add_patch(plt.Rectangle(
            (current_x + left_border, current_y + bottom_border),
            inner_width, inner_height,
            color='white'
        ))
        
        # 绘制四个边框
        # 左边框
        ax.add_patch(plt.Rectangle(
            (current_x, current_y),
            left_border, total_height,
            color='black'
        ))
        # 右边框
        ax.add_patch(plt.Rectangle(
            (current_x + left_border + inner_width, current_y),
            right_border, total_height,
            color='black'
        ))
        # 下边框
        ax.add_patch(plt.Rectangle(
            (current_x, current_y),
            total_width, bottom_border,
            color='black'
        ))
        # 上边框
        ax.add_patch(plt.Rectangle(
            (current_x, current_y + bottom_border + inner_height),
            total_width, top_border,
            color='black'
        ))
        
        # 更新x坐标,为下一个单元格做准备
        current_x += total_width
    
    # 更新y坐标,为下一行做准备
    current_y += total_height

# 调整坐标轴范围适配所有单元格
ax.set_xlim(0, current_x)
ax.set_ylim(0, current_y)
plt.gca().invert_yaxis()  # 反转y轴,让第一行显示在画布顶部
plt.show()

关键说明

  • 坐标跟踪逻辑:current_x和current_y始终指向下一个单元格的左下角起始位置,每个单元格绘制完成后累加自身总尺寸,确保相邻单元格无缝贴合
  • 绘制顺序:先画内部白色区域,再覆盖绘制边框,避免边框与内部区域出现缝隙
  • y轴反转:适配常规视觉习惯,让网格的第一行显示在画布顶部而非底部

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:01:07