如何在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
相关产品推荐
相关产品推荐

