【问题标题】:How to add spacing between each block of a heatmap如何在热图的每个块之间添加间距
【发布时间】:2022-12-05 21:49:19
【问题描述】:

我有一个这样的矩阵。有没有一种方法可以在不改变缩放比例的情况下在它之间添加一些白线。我为此图使用了 matplotlib:

这样的事情应该有效。:

代码 ->

# final heatmap code with correct color range
import matplotlib.pyplot as plt
import numpy as np


def heatmap2d(arr: np.ndarray):
    plt.imshow(arr, cmap='jet', interpolation = "none",vmin = 140, vmax = 395)
    plt.colorbar()
    plt.show()


test_array = [
     [220, 152, 146, 151, 146, 144],
     [142, 156, 290, 174, 152, 151],
     [148, 190, 390, 370, 146, 152],
     [143, 142, 380, 375, 146, 152],
     [154, 146, 154, 172, 150, 152],
     [150, 152, 144, 140, 142, 0]
 ]
heatmap2d(test_array)

【问题讨论】:

    标签: python matplotlib seaborn heatmap


    【解决方案1】:

    Seaborn 让这一切变得非常简单。调用sns.heatmap,并传递linewidths参数。

    import seaborn as sns
    import numpy as np
    
    
    def heatmap2d(arr: np.ndarray):
        sns.heatmap(test_array, linewidths=20, square=True, vmin=140, vmax=395, cmap='jet')
    
    
    test_array = [
         [220, 152, 146, 151, 146, 144],
         [142, 156, 290, 174, 152, 151],
         [148, 190, 390, 370, 146, 152],
         [143, 142, 380, 375, 146, 152],
         [154, 146, 154, 172, 150, 152],
         [150, 152, 144, 140, 142, 0]
     ]
    heatmap2d(test_array)
    

    【讨论】:

      【解决方案2】:

      按照the tutorial of matplotlib,您可以在轴上添加额外的小刻度,并在这些小刻度上应用白色网格。它会对您的热图产生填充效果,例如绘图

      # Turn spines off and create white grid.
      ax.spines[:].set_visible(False)
      ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
      ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
      ax.grid(which="minor", color="w", linestyle='-', linewidth=3) # change the appearance of your padding here
      ax.tick_params(which="minor", bottom=False, left=False)
      

      【讨论】:

        猜你喜欢
        • 2013-09-15
        • 2011-09-07
        • 2020-04-08
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-16
        • 1970-01-01
        相关资源
        最近更新 更多