如何使用Pyplot绘制具有不同线宽的网格(细胞分隔场景)
用Matplotlib Pyplot绘制带不同线宽分隔壁的细胞网格
需求:绘制一个细胞网格,细胞之间互不连通,被5种不同厚度的“壁”分隔开。
用户尝试的代码:
rows, cols = self.lignes, self.colonnes fig, ax = plt.subplots(rows, cols, sharex='col', sharey='row') for row in range(rows): for col in range(cols): ax[row, col].text(0.5, 0.5, str((row, col)), color="green", fontsize=18, ha='center') plt.axis('on') plt.show()
解决方案
原有的子图布局很难单独控制每个分隔壁的线宽,建议在单个坐标轴上直接绘制所有壁和细胞标签,这样能灵活设置每条线的厚度。
完整示例代码:
import matplotlib.pyplot as plt import numpy as np # 网格行列数,可替换为self.lignes和self.colonnes rows, cols = 3, 3 # 定义5种不同的壁厚度 wall_widths = [0.5, 1, 2, 3, 4] # 模拟各细胞四个方向的壁类型(0-4对应上面的厚度),实际使用时替换为真实数据 top_walls = np.random.randint(0, 5, size=(rows, cols)) bottom_walls = np.random.randint(0, 5, size=(rows, cols)) left_walls = np.random.randint(0, 5, size=(rows, cols)) right_walls = np.random.randint(0, 5, size=(rows, cols)) cell_size = 1 # 单个细胞的边长 fig, ax = plt.subplots(figsize=(8, 8)) # 设置坐标轴范围以适配整个网格 ax.set_xlim(0, cols * cell_size) ax.set_ylim(0, rows * cell_size) ax.axis('off') # 关闭默认坐标轴,避免干扰网格显示 for row in range(rows): for col in range(cols): # 计算当前细胞的四个顶点坐标 x_left = col * cell_size x_right = (col + 1) * cell_size y_bottom = row * cell_size y_top = (row + 1) * cell_size # 绘制左侧壁,匹配对应厚度 ax.plot([x_left, x_left], [y_bottom, y_top], color='black', linewidth=wall_widths[left_walls[row, col]]) # 绘制右侧壁 ax.plot([x_right, x_right], [y_bottom, y_top], color='black', linewidth=wall_widths[right_walls[row, col]]) # 绘制下侧壁 ax.plot([x_left, x_right], [y_bottom, y_bottom], color='black', linewidth=wall_widths[bottom_walls[row, col]]) # 绘制上侧壁 ax.plot([x_left, x_right], [y_top, y_top], color='black', linewidth=wall_widths[top_walls[row, col]]) # 在细胞中心添加坐标标签 ax.text(x_left + cell_size/2, y_bottom + cell_size/2, str((row, col)), color='green', fontsize=18, ha='center') plt.tight_layout() plt.show()
代码说明
- 用
wall_widths定义5种不同的壁厚度,top_walls等数组存储每个细胞各方向的壁类型,实际开发中可替换为业务逻辑生成的真实数据。 - 在单个坐标轴上绘制所有壁,每条线的厚度由对应壁类型决定,完美实现不同厚度的分隔效果。
- 保留原代码中细胞中心的坐标标签逻辑,确保显示效果一致。
内容的提问来源于stack exchange,提问作者SomeoneElse
相关产品推荐
相关产品推荐

