python - python中的单行(或列)热图

标签 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('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)。 这是我想要生成的示例图像:

enter image description here

提前致谢。

最佳答案

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

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

enter image description here

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

关于python - python中的单行(或列)热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43076488/

相关文章:

python - 迭代数据框中的某些列

python - Pandas DataFrame 列的 boolean 掩码

python - 如何使用线程正确结束程序?

python - 如何用线连接非纳米值?

javascript - 谷歌热图 - map 上没有指针

python - 为我的热图添加图例

python - 如何定位NetworkX中巨型组件的中心节点?

python - plotly 属性错误: 'Figure' object has no attribute 'show'

python - tsplot 的颜色 basemap

r - 如何从 ggplot2 的热图函数中提取多边形?