使用seaborn 热图突出显示每行的最小值

2024-03-31

我试图使用相同的颜色突出显示每行的最小值:

例如,第一行最小值为 0.3。我想用蓝色突出显示它。同样,对于第二行,0.042 等等。

这是代码。

import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
from matplotlib.patches import Rectangle

Pe = np.random.rand(5,5)

annot=True
fig, ax1 = plt.subplots(1)    
ax1 = sns.heatmap(Pe, linewidth=0.5,ax=ax1,annot=annot)

您可以循环遍历各行,找到最小值的索引,然后在其中绘制一个矩形。环境clip_on=False防止矩形被边框剪切。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

Pe = np.random.rand(5, 5)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 4))
sns.set_style('white')

sns.heatmap(Pe, linewidth=0.5, annot=True, ax=ax1)
for ind, row in enumerate(Pe):
    min_col = np.argmin(row)
    ax1.add_patch(plt.Rectangle((min_col, ind), 1, 1, fc='none', ec='skyblue', lw=5, clip_on=False))

sns.heatmap(Pe, mask=Pe != Pe.min(axis=1, keepdims=True), annot=True, lw=2, linecolor='black', clip_on=False,
            cmap=ListedColormap(['skyblue']), cbar=False, ax=ax2)
plt.tight_layout()
plt.show()

PS:要制作动画,赛璐珞库 https://github.com/jwkvam/celluloid是一个轻量级的选项:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import numpy as np
from celluloid import Camera

Pe = np.random.rand(5, 5)

fig, ax1 = plt.subplots()
camera = Camera(fig)
sns.set_style('white')

row_array = np.arange(Pe.shape[0]).reshape(-1, 1)
for row in range(Pe.shape[0]):
    sns.heatmap(Pe, mask=(Pe != Pe.min(axis=1, keepdims=True)) | (row < row_array),
                annot=True, lw=2, linecolor='black', clip_on=False,
                cmap=ListedColormap(['skyblue']), cbar=False, ax=ax1)
    camera.snap()

animation = camera.animate(interval=800)
animation.save('animation.gif')
plt.show()

对于更复杂的动画,matplotlib动画API https://matplotlib.org/stable/api/animation_api.html可以考虑。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用seaborn 热图突出显示每行的最小值 的相关文章

随机推荐