【问题标题】:Single row (or column) heat map in pythonpython中的单行(或列)热图
【发布时间】:2017-08-21 22:28:17
【问题描述】:

我可以使用以下代码创建 n×n 热图,例如让 n 为 10:

random_matrix = np.random.rand(10,10)
number = 10
incrmnt = 1.0
x = list(range(1,number +1))
plt.pcolormesh(x, x, random_matrix)
plt.colorbar() 
plt.xlim(1, number)
plt.xlabel('Number 1')
plt.ylim(1, number)
plt.ylabel('Number 2')
plt.tick_params(
    axis = 'both',
    which = 'both',
    bottom = 'off',
    top = 'off', 
    labelbottom = 'off', 
    right = 'off',
    left = 'off',
    labelleft = 'off')

我想在 x 轴和 y 轴附近添加一个 2 行热图,例如 row1 = np.random.rand(1,10)col1 = np.random.rand(1,10)。 这是我想要制作的示例图片:

提前致谢。

【问题讨论】:

  • 还有一个很similar question询问如何在不同位置“剪切”热图,以防有人感兴趣。

标签: python matplotlib heatmap


【解决方案1】:

您将创建一个子图网格,其中子图之间的宽高比对应于相应维度中的像素数。然后,您可以将相应的图添加到这些子图中。在下面的代码中,我使用了imshow 图,因为我发现数组中的每个项目都有一个像素(而不是少一个)更直观。

为了让颜色条代表不同子图的颜色,可以使用提供给每个子图的matplotlib.colors.Normalize 实例,以及为颜色条手动创建的 ScalarMappable。

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

m = np.random.rand(10,10)
x = np.random.rand(1,m.shape[1])
y = np.random.rand(m.shape[0],1)

norm = matplotlib.colors.Normalize(vmin=0, vmax=1)
grid = dict(height_ratios=[1, m.shape[0]], width_ratios=[1,m.shape[0], 0.5 ])
fig, axes = plt.subplots(ncols=3, nrows=2, gridspec_kw = grid)

axes[1,1].imshow(m, aspect="auto", cmap="viridis", norm=norm)
axes[0,1].imshow(x, aspect="auto", cmap="viridis", norm=norm)
axes[1,0].imshow(y, aspect="auto", cmap="viridis", norm=norm)

axes[0,0].axis("off")
axes[0,2].axis("off")

axes[1,1].set_xlabel('Number 1')
axes[1,1].set_ylabel('Number 2')
for ax in [axes[1,1], axes[0,1], axes[1,0]]:
    ax.set_xticks([]); ax.set_yticks([])

sm = matplotlib.cm.ScalarMappable(cmap="viridis", norm=norm)
sm.set_array([])

fig.colorbar(sm, cax=axes[1,2]) 

plt.show()

【讨论】:

  • 效果很好,谢谢。虽然当我在我的数据方面使用上面的代码时 = "auto" 将每个点变成一个矩形而不是一个正方形。当我尝试指定 aspect = 1 时,情节相距太远。有什么建议吗?
  • 好吧,您需要调整图形大小和间距,以便保留图像的外观。在other question我做了一些粗略的改编。一个完美的解决方案将涉及类似于this question 的内容。但简单地将图形大小设置为接近数组的方面也可能就足够了,例如如果您有一个 5 x 20 的数组,请将图形高度设置为宽度的四分之一。
猜你喜欢
  • 1970-01-01
  • 2018-02-04
  • 2018-05-15
  • 1970-01-01
  • 2021-01-16
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多