如何向热图添加图例

huangapple go评论77阅读模式
英文:

How to add a legend to a heatmap

问题

我使用了这个 非常好的代码 的一个小变化来绘制热图。

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

# 将下限颜色设置为白色
cmap.set_under("white")

# 将上限颜色设置为黑色
cmap.set_over("black")

# 设置背景颜色

g = sns.heatmap(A, vmin=10, vmax=90, cmap=cmap, mask=mask_array)
# 设置掩码区域的颜色
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)

结果如下:

如何向热图添加图例

现在用RGB (1.0000, 0.2716, 0.0000) 表示值为20的正方形,这表示实验失败。我想添加一个图例,其中有这种颜色的正方形和单词“broken”。它必须放在热图外面,以免遮挡它。我该怎么做?

英文:

I am using a small variation of this really nice code to plot a heatmap.

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)

The result looks like:

如何向热图添加图例

The squares that had the value 20 and so are now colored with RGB (1.0000, 0.2716, 0.0000) indicate that the experiment was broken. I would like to add a legend that has a square of that color and the word "broken" next to it. It will have to be outside the heatmap so as not to obscure it. How can I do that?

答案1

得分: 3

以下是您要翻译的内容:

"你可以创建自己想要的颜色的矩形,并将其传递给图例方法。如果您想要移动图例,可以使用 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()

# 将底色设置为白色
cmap.set_under("white")

# 将顶色设置为黑色
cmap.set_over("black")

# 设置背景颜色

g = sns.heatmap(A, vmin=10, vmax=90, cmap=cmap, mask=mask_array)
# 设置掩码区域的颜色
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()
英文:

You can make your own rectangle with the color you want and feed it into the legend method. If you want to move the legend around then you can use the loc and bbox_to_anchor arguments- see the legend guide for more info on these 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))

如何向热图添加图例

Inserting all of the code you already have...

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

huangapple
  • 本文由 发表于 2023年6月13日 05:27:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定