【问题标题】:Divide cell of heatmap in multiple rows将热图的单元格分成多行
【发布时间】:2021-08-12 19:56:07
【问题描述】:

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

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

我尝试使用以下链接,但没有成功分成 3 行: How to create a heatmap where each cell is divided into 4 triangles?

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

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()

感谢所有帮助,问候!

【问题讨论】:

    标签: python matplotlib data-visualization heatmap


    【解决方案1】:

    当将单元格划分为 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()
    

    【讨论】:

    • 非常感谢你,这太棒了,现在我可以继续添加数据了
    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    相关资源
    最近更新 更多