如何绘制由轴坐标定义间距的热图/相图

问题描述 投票:0回答:2

我正在尝试绘制一个相图,其中正方形的面积由 x,y 轴坐标定义,而不是等距。

例如我有以下数组:

import numpy as np

x = np.array([ 10,  50, 100, 150])
y = np.array([100,  80,  60,  40,  20,  10,   5])
z = np.array([[0.31, 0.33, 0.34 , 0.34],
       [0.31, 0.34, 0.34, 0.34],
       [0.30, 0.34, 0.35, 0.34],
       [0.30, 0.33, 0.34 , 0.34],
       [0.29, 0.31, 0.31, 0.31],
       [0.29, 0.30, 0.30, 0.29],
       [0.28 , 0.28, 0.28 , 0.29]])

我尝试使用 sns.heatmap() 将其绘制为数据框,但我无法更改要根据 x,y 坐标而不是同等大小调整大小的正方形面积。

我得到这个结果:

热图

我还尝试遵循我在这里找到的建议:绘制 2D 热图 使用此处修改的代码如下,但这样区域不同但不太正确:

import matplotlib.pyplot as plt
import numpy as np



z_min, z_max = np.abs(z).min(), np.abs(z).max()

fig, ax = plt.subplots()

c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max, shading='auto', edgecolors='black')
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)

plt.show()

给出了这个结果,这似乎几乎是我想要的,但正方形的尺寸不正确,我不太明白为什么:

pcolormesh

如果我还可以用每个方块的实际值来注释绘图,那就太好了!

python matplotlib heatmap
2个回答
1
投票

x
y
pcolormesh
表示单元格之间edges的位置。如果水平方向有 4 个单元格,则有 5 个边缘。

假设您给定的

x
y
是单元格宽度,您可以使用
np.cumsum()
来计算边缘位置。

import matplotlib.pyplot as plt
import numpy as np

x = np.array([10, 50, 100, 150])
y = np.array([100, 80, 60, 40, 20, 10, 5])
z = np.array([[0.31, 0.33, 0.34, 0.34],
              [0.31, 0.34, 0.34, 0.34],
              [0.30, 0.34, 0.35, 0.34],
              [0.30, 0.33, 0.34, 0.34],
              [0.29, 0.31, 0.31, 0.31],
              [0.29, 0.30, 0.30, 0.29],
              [0.28, 0.28, 0.28, 0.29]])

fig, ax = plt.subplots()

x_edges = np.append([0], x.cumsum())
y_edges = np.append([0], y.cumsum())
c = ax.pcolormesh(x_edges, y_edges, z, cmap='RdBu', shading='auto', edgecolors='black')
ax.set_title('pcolormesh')
fig.colorbar(c, ax=ax)

plt.tight_layout()
plt.show()

边缘可用于计算细胞中心的位置,例如用 x 和 y 数量标记行和列。

x_mids = (x_edges[:-1] + x_edges[1:]) / 2
y_mids = (y_edges[:-1] + y_edges[1:]) / 2
ax.set_xticks(x_mids, x)
ax.set_yticks(y_mids, y)


0
投票
import matplotlib.pyplot as plt
import numpy as np

x = np.array([10, 50, 100, 150])
y = np.array([100, 80, 60, 40, 20, 10, 5])
z = np.array([[0.31, 0.33, 0.34, 0.34],
              [0.31, 0.34, 0.34, 0.34],
              [0.30, 0.34, 0.35, 0.34],
              [0.30, 0.33, 0.34, 0.34],
              [0.29, 0.31, 0.31, 0.31],
              [0.29, 0.30, 0.30, 0.29],
              [0.28, 0.28, 0.28, 0.29]])

fig, ax = plt.subplots()

x_edges = np.append([0], x)#.cumsum())
y_edges = np.append([0], y)#.cumsum())

c = ax.pcolormesh(x_edges, y_edges, z, cmap='RdBu', shading='auto', edgecolors='black')

ax.set_xticks(x_edges[1:], x)
ax.set_yticks(y_edges[1:], y)

ax.set_title('pcolormesh')
fig.colorbar(c, ax=ax)


plt.tight_layout()
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.