首页 > 解决方案 > 将热图的单元格分成多行

问题描述

我正在使用热图,每个单元格有 3 行数据,现在,我想将每个单元格分成 3 行,每行数据一个,

在此处输入图像描述

这样,每一行都会根据值有自己的颜色

我正在尝试使用以下链接,但我没有成功划分为 3 行: 如何创建一个热图,其中每个单元格分为 4 个三角形?

出于这个原因,我去这个空间寻求帮助以便能够进行这个修改,我包含了我修改过的代码,它属于我之前提到的链接,

from matplotlib import pyplot as plt
import numpy as np

M, N = 4,4
values = np.random.uniform(9, 10, (N * 1, M * 2))

fig, ax = plt.subplots()
#ax.imshow(values, extent=[-0.5, M - 0.5, N - 0.5,-0.5], cmap='autumn_r')
ax.imshow(values, extent=[-0.5,M - 0.5, N - 0.5,-0.5], cmap='autumn_r')

ax.set_xticks(np.arange(0, 4))
ax.set_xticks(np.arange(-0.5, M), minor=True)
ax.set_yticks(np.arange(0, 4))
ax.set_yticks(np.arange(-0.5, N), minor=True)
ax.grid(which='minor', lw=6, color='w', clip_on=True)
ax.grid(which='major', lw=2, color='w', clip_on=True)
ax.tick_params(length=0)
for s in ax.spines:
    ax.spines[s].set_visible(True)
plt.show()

我感谢所有的帮助,问候!

标签: pythonmatplotlibdata-visualizationheatmap

解决方案


将单元格划分为 2 时,主要刻度位置可用于设置标签和定位细分线。要分成 3 个或更多,明确地绘制水平线和垂直线可能更容易。

这是一些示例代码:

from matplotlib import pyplot as plt
import numpy as np

M, N = 4, 4  # M columns and N rows of large cells
K, L = 1, 3  # K columns and L rows to subdivide each of the cells
values = np.random.uniform(9, 10, (N * L, M * K))

fig, ax = plt.subplots()
ax.imshow(values, extent=[-0.5, M - 0.5, N - 0.5, -0.5], cmap='autumn_r')

# positions for the labels
ax.set_xticks(np.arange(0, M))
ax.set_yticks(np.arange(0, N))

# thin lines between the sub cells
for i in range(M):
    for j in range(1, K):
        ax.axvline(i - 0.5 + j / K, color='white', lw=2)
for i in range(N):
    for j in range(1, L):
        ax.axhline(i - 0.5 + j / L, color='white', lw=2)
# thick line between the large cells
# use clip_on=False and hide the spines to avoid that the border cells look different
for i in range(M + 1):
    ax.axvline(i - 0.5, color='skyblue', lw=4, clip_on=False)
for i in range(N + 1):
    ax.axhline(i - 0.5, color='skyblue', lw=4, clip_on=False)
ax.tick_params(length=0)
for s in ax.spines:
    ax.spines[s].set_visible(False)
plt.show()

带有额外细分的热图


推荐阅读