python中的单行(或列)热图

python中的单行(或列)热图,python,matplotlib,heatmap,Python,Matplotlib,Heatmap,我可以使用以下代码创建和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('Nu

我可以使用以下代码创建和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轴附近添加一个两行的热图,比如说
row1=np.random.rand(1,10)
col1=np.random.rand(1,10)
。 以下是我想制作的示例图像:


提前感谢。

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

为了让colorbar表示不同子批次之间的颜色,可以使用
matplotlib.colors.Normalize
实例(提供给每个子批次)以及为colorbar手动创建的ScalarMapable


还有一个问题是,如果有人感兴趣,如何在不同的位置“切割”热图。效果很好,谢谢。虽然当我在data aspect=“auto”上使用上述代码时,会将每个点变成矩形而不是正方形。当我尝试指定aspect=1时,绘图距离太远。有什么建议吗?嗯,你需要调整体形的大小和间距,这样才能保留图像的外观。最后,我做了一些粗略的改编。一个完美的解决方案将涉及类似于中的内容。但也可以简单地将图形大小设置为接近阵列的纵横比,例如,如果您有一个5 x 20阵列,则将图形高度设置为宽度的四分之一。
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()