matplotlib 如何将图例添加到热图

nle07wnf  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(69)

我使用这个really nice code的一个小变体来绘制热图。

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

np.random.seed(7)
A = np.random.randint(0,100, size=(20,20))
mask_array = np.zeros((20, 20), dtype=bool)
mask_array[:, :5] = True
# cmap = matplotlib.colormaps["viridis"]
cmap = matplotlib.cm.get_cmap('viridis').copy()

# Set the under color to white
cmap.set_under("white")

# Set the over color to white
cmap.set_over("black")

# Set the background color

g = sns.heatmap(A, vmin=10, vmax=90, cmap=cmap, mask=mask_array)
# Set color of masked region
g.set_facecolor('lightgrey')

cbar_ax = g.figure.axes[-1]

for spine in cbar_ax.spines.values():
    spine.set(visible=True)
    
special_data = np.ma.masked_where(A==20, A)
sns.heatmap(special_data, cmap=ListedColormap((1.0000, 0.2716, 0.0000)), 
            mask=(special_data != 1), cbar=False)

结果如下所示:

值为20的正方形现在用RGB(1.0000,0.2716,0.0000)着色,表明实验被破坏。我想添加一个图例,它有一个正方形的颜色和单词“破碎”旁边。它必须在热图之外,以免模糊它。我该怎么做?

4nkexdtk

4nkexdtk1#

您可以使用您想要的颜色创建自己的矩形,并将其输入到图例方法中。如果你想移动图例,那么你可以使用locbbox_to_anchor参数-关于这些https://matplotlib.org/stable/tutorials/intermediate/legend_guide.html的更多信息,请参阅图例指南

from matplotlib.patches import Rectangle

# ...

rect = Rectangle((0, 0), 0, 0, color=(1.0000, 0.2716, 0.0000))
g.legend(handles=[rect], labels=['Broken'], loc='lower right', bbox_to_anchor=(1, 1))

正在插入您已有的所有代码...

import matplotlib
import seaborn as sns
import numpy as np
from matplotlib.colors import ListedColormap
from matplotlib.pyplot import show
from matplotlib.patches import Rectangle

np.random.seed(7)
A = np.random.randint(0,100, size=(20,20))
mask_array = np.zeros((20, 20), dtype=bool)
mask_array[:, :5] = True
# cmap = matplotlib.colormaps["viridis"]
cmap = matplotlib.cm.get_cmap('viridis').copy()

# Set the under color to white
cmap.set_under("white")

# Set the over color to white
cmap.set_over("black")

# Set the background color

g = sns.heatmap(A, vmin=10, vmax=90, cmap=cmap, mask=mask_array)
# Set color of masked region
g.set_facecolor('lightgrey')

cbar_ax = g.figure.axes[-1]

for spine in cbar_ax.spines.values():
    spine.set(visible=True)

special_data = np.ma.masked_where(A==20, A)
sns.heatmap(special_data, cmap=ListedColormap((1.0000, 0.2716, 0.0000)),
            mask=(special_data != 1), cbar=False, ax=g)

rect = Rectangle((0, 0), 0, 0, color=(1.0000, 0.2716, 0.0000))
g.legend(handles=[rect], labels=['Broken'], loc='lower right', bbox_to_anchor=(1, 1))

show()

相关问题