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

如何解决matplotlib pcolormesh单元格白色间隙并设置为20x20?

解决pcolormesh单元格间隙与20x20尺寸设置问题

核心问题

你当前代码按1单位步长生成坐标序列,导致pcolormesh默认渲染1x1的单元格,再加上偏移处理错误,最终出现白色间隙,且单元格尺寸不符合20x20的要求。

修正方案

  1. 按20单位步长生成有效坐标
    直接以20为间隔提取eastings和northings,匹配你的单元格实际间距,避免生成大量无效的1单位坐标点。
  2. 正确定义单元格边界
    pcolormesh的x和y参数需要传入单元格的边界值,而非左上角坐标。对于左上角为(x,y)、尺寸20x20的单元格,右边界是x+20,下边界是y-20(northing轴向上递增)。
  3. 优化数据匹配逻辑
    用pandas透视表替代循环查询,更高效地构建20x20单元格对应的数值矩阵。

修改后的代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# 自定义色卡
cmap0 = LinearSegmentedColormap.from_list('', ['white', 'darkblue'])

# 按20单位步长提取有效坐标(匹配单元格左上角)
east_min = df275.E.min()
east_max = df275.E.max()
eastings = np.arange(east_min, east_max + 20, 20)  # 包含右边界,步长20

north_min = df275.N.min()
north_max = df275.N.max()
northings = np.arange(north_min, north_max + 20, 20)  # 包含上边界,步长20

# 用透视表构建z矩阵,缺失值填充0
z_matrix = df275.pivot_table(index='N', columns='E', values='2', fill_value=0)
# 确保z矩阵的行列顺序与坐标序列一致
z_matrix = z_matrix.reindex(index=northings, columns=eastings, fill_value=0)

fig, ax = plt.subplots(1, 1, figsize=(8,10))

# 定义单元格边界:x包含所有左边界+最后一个右边界;y包含所有上边界+最后一个下边界
x_bounds = np.append(eastings, eastings[-1] + 20)
y_bounds = np.append(northings, northings[-1] - 20)

# 绘制20x20的单元格
ax.pcolormesh(x_bounds, y_bounds, z_matrix.values, cmap=cmap0, vmin=0, vmax=df275['2'].max())

# 设置轴标签、标题与刻度对齐
ax.set(xlabel="Easting", ylabel="Northing")
ax.set_title(f"Period 2")
ax.set_xticks(eastings)
ax.set_yticks(northings)

plt.show()

关键说明

  • np.arange生成坐标时,额外添加20的偏移是为了覆盖最后一个单元格的边界,确保绘图区域完整。
  • pivot_table替代循环查询,既提升效率又避免手动填充数据时的错误。
  • 明确传入单元格边界值,强制pcolormesh渲染20x20的单元格,彻底消除白色间隙。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:53:27