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

如何为matplotlib网格指定单元格着色并调整网格内箭头居中

问题解决代码及说明
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

arrow_direction_per_cell = {(0, 0): 'RIGHT',(0, 1): 'DOWN',(0, 2): 'UP',(0, 3): 'LEFT',(0, 4): 'UP',
 (1, 0): 'RIGHT',(1, 1): 'RIGHT',(1, 2): 'DOWN',(1, 3): 'LEFT', (1, 4): 'LEFT',(2, 0): 'RIGHT',(2, 1): 'RIGHT',
 (2, 2): 'DOWN',(2, 3): 'LEFT',(2, 4): 'UP',(3, 0): 'LEFT',(3, 1): 'RIGHT',(3, 2): 'UP',(3, 3): 'LEFT',(3, 4): 'UP',
 (4, 0): 'LEFT',(4, 1): 'DOWN', (4, 2): 'UP',(4, 3): 'UP', (4, 4): 'UP'}

# 适配倒置y轴的方向映射,y轴数值越小越靠上
direction_map = {'UP':(0,-1),'DOWN':(0,1),'RIGHT':(1,0),'LEFT':(-1,0)}

locations = arrow_direction_per_cell.keys()

fig, ax = plt.subplots(figsize=(6,6))
plt.xlim(0, 5)
plt.ylim(5, 0)
plt.grid(True)
plt.xticks(np.arange(0, 6, 1.0))
plt.yticks(np.arange(0, 6, 1.0))

# 填充指定单元格颜色
cells_to_be_orange = [(0,2),(2,4),(3,4)]
cells_to_be_blue = [(3,2)]
for (x,y) in cells_to_be_orange:
    ax.add_patch(Rectangle((x, y), 1, 1, facecolor='orange', alpha=0.3))
for (x,y) in cells_to_be_blue:
    ax.add_patch(Rectangle((x, y), 1, 1, facecolor='blue', alpha=0.3))

# 绘制居中箭头
for location in locations:
    arrow_direction = arrow_direction_per_cell[location]
    # 单元格中心坐标计算正确,保持不变
    x_pos,y_pos = (location[0]+.5),(location[1]+.5)
    x_direct,y_direct = direction_map[arrow_direction]
    # quiver参数调整:pivot设为mid让箭头中点对齐中心,scale调整箭头长度,units设为xy适配坐标系
    ax.quiver(x_pos, y_pos, x_direct, y_direct, pivot='mid', scale=8, units='xy')

plt.show()

问题解决说明

  • 单元格填充实现:
    导入Rectangle矩形绘制类,单元格的左下角坐标为(单元格x索引, 单元格y索引),宽高均为1,设置facecolor指定填充颜色,alpha参数调整透明度避免遮盖箭头,通过ax.add_patch()将矩形添加到画布即可。
  • 箭头居中调整:
    1. 修正方向映射:你设置了ylim(5, 0)将y轴倒置,y数值越小位置越靠上,因此原来的UP/DOWN对应的y方向偏移需要反转,避免箭头方向和预期不符。
    2. 调整quiver参数:新增pivot='mid'参数,让箭头的中点和你计算的单元格中心坐标(x_pos,y_pos)对齐;新增units='xy'让箭头尺寸适配当前坐标系,调整scale参数控制箭头长度,避免箭头超出单元格范围。
    3. 删除了你代码末尾冗余的ax.quiver(x_pos, y_pos, x_direct, y_direct)语句,避免额外绘制多余箭头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:12:02