如何强制 matplotlib 热图单元格为矩形?

How to force matplotlib heatmap cells to be rectangular?

我正在使用 pcolormesh 创建热图。

heatmap = plt.pcolormesh(
    grid,
    edgecolors="k",
    cmap=colors.ListedColormap(
        [
            "white",
            "red",
            "blue",
            "green",
            "orange",
            "black",
            "purple",
            "yellow",
            "brown",
            "violet",
            "gray",
        ]
    ),
    linewidth=2,
)
ax = plt.gca()
ax.set_aspect("auto")

我想将单元格形状设置为矩形。我该怎么做?

我猜你指的是“方形”单元格,而不是“矩形”单元格:

将纵横比设置为 1:ax.set_aspect(1)

aspect 定义了 Y/X 比率,因此要有两倍高的单元格:ax.set_aspect(2)

加倍宽:ax.set_aspect(1/2)