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

如何在Matplotlib中绘制单元格为方形的pcolor图?

How to Create Square Cells in Matplotlib's pcolor Plot

Absolutely! The rectangular cells you're seeing happen because Matplotlib automatically scales the x and y axes based on your data's range, which stretches the cells unevenly. To fix this, you just need to enforce equal scaling for both axes so each unit on x matches each unit on y visually.

Here's how to modify your code:

import matplotlib.pyplot as plt
import numpy as np  # Adjust if you're using scipy's meshgrid instead

# Replace with your actual x, y, z data
x = np.linspace(0, 5, 6)
y = np.linspace(0, 5, 6)
z = np.random.rand(5, 5)  # Note: pcolor expects z to be one dimension smaller than X/Y

fig = plt.figure()
X, Y = np.meshgrid(x, y)
plt.pcolor(X, Y, z, edgecolors='k', linewidths=1, snap=True)
plt.colorbar()

# This is the key line to make cells square
plt.axis('equal')

# Alternatively, for more control (great if x/y ranges are very different):
# ax = plt.gca()
# ax.set_aspect('equal', adjustable='box')

plt.show()

What's going on here?

  • plt.axis('equal') forces Matplotlib to display each unit of x and y with the same physical length on the screen. No matter how your x and y ranges compare, this will make every cell in the pcolor grid a perfect square.
  • If your x and y data have drastically different ranges (like x spanning 0-100 while y spans 0-10), using ax.set_aspect('equal', adjustable='box') will adjust the overall figure size to fit the square cells without leaving huge empty spaces.

Give this a try—it should fix the rectangular cell issue right away!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:10:07