具有可变单元大小的Seaborn热图

时间:2020-10-14 15:34:19

标签: python matplotlib seaborn

我有一个带有刻度的热图,它们之间的增量不相等: enter image description here

例如,在所附图像中,增量在0.015至0.13之间。由于所有像元大小均相等,因此当前比例未显示实际情况。

是否有一种方法可以将刻度线放置在其实际位置,以使像元大小也相应地变化? 或者,是否存在另一种方法来生成该图,使其能够提供刻度值的真实表示?

1 个答案:

答案 0 :(得分:2)

如评论中所述,Seaborn热图使用分类标签。但是,底层结构是pcolormesh,每个单元格的大小可以不同。

注释中还提到,不建议更新pcolormesh的私有属性。此外,可以通过调用pcolormesh直接创建热图。

请注意,如果有N个像元,则将有N + 1个边界。下面的示例代码假定您在单元格的中心具有x位置。然后,它计算连续单元之间的中间边界。重复第一个和最后一个距离。

可以从给定的x值设置x和y轴的刻度和刻度标签。该示例代码假设原始值指示单元格的中心。

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

sns.set()
N = 10
xs = np.random.uniform(0.015, 0.13, 10).cumsum().round(3)  # some random x values
values = np.random.rand(N, N)  # a random matrix

# set bounds in the middle of successive cells, add extra bounds at start and end
bounds = (xs[:-1] + xs[1:]) / 2
bounds = np.concatenate([[2 * bounds[0] - bounds[1]], bounds, [2 * bounds[-1] - bounds[-2]]])

fig, ax = plt.subplots()
ax.pcolormesh(bounds, bounds, values)

ax.set_xticks(xs)
ax.set_xticklabels(xs, rotation=90)
ax.set_yticks(xs)
ax.set_yticklabels(xs, rotation=0)
plt.tight_layout()
plt.show()

example heatmap

PS:如果要把刻度线作为边界,则可以简化代码。需要一个额外的边界,例如开始时为零。

bounds = np.concatenate([[0], xs])
ax.tick_params(bottom=True, left=True)

example with ticks between the cells