[英]How to annotate specific cells in a heatmap?
How can I just annotate the four corner cells?我怎样才能只注释四个角单元格?
for N in Nvals:
for R in Rvals:
filename = "data"
filename += "-N" + str(N) + "-R0" + str(R)
filename += ".txt"
data = []
with open(filename) as file:
for line in file.readlines():
#line = line.strip('"\'`(), False True \n')
try:
value = float(line)
except ValueError:
pass
else:
data.append(value)
data = np.array(data)
mean.append(np.mean(data))
mean = np.array(mean).reshape(11,10)
plt.figure(1)
plt.figure(figsize=(3,3), dpi=175)
res=sns.heatmap(mean,square=True,
norm=LogNorm(0.01, 100),
annot=True,annot_kws={'size': 4},
xticklabels=False, yticklabels=False,
cbar = False,
cmap="viridis_r")
res.invert_yaxis()
Seaborn's heatmap
allows to explicitly give a 2D array to be used as annotations. Seaborn 的
heatmap
允许明确给出一个二维数组作为注释。 For example, you can create a list of lists with all empty strings except at the corners:例如,您可以创建一个列表列表,其中包含除角落之外的所有空字符串:
from matplotlib import pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np
import seaborn as sns
mean = 100 ** np.random.rand(11, 10)
plt.figure(1, figsize=(3, 3), dpi=175)
annot_values = np.full_like(mean, np.nan)
for i, j in [(0, 0), (0, -1), (-1, 0), (-1, -1)]:
annot_values[i, j] = mean[i, j]
m, n = mean.shape
annot_values = [[f'{mean[i, j]:.2g}' if i in (0, m - 1) and j in (0, n - 1) else ''
for j in range(n)]
for i in range(m)]
ax = sns.heatmap(mean, square=True,
norm=LogNorm(0.01, 100),
annot=annot_values, annot_kws={'size': 10}, fmt="s",
xticklabels=False, yticklabels=False,
cbar=False,
cmap="viridis_r")
ax.invert_yaxis()
plt.tight_layout()
plt.show()
PS: Note that each time you call plt.figure()
you create a new figure. PS:请注意,每次调用
plt.figure()
时都会创建一个新图形。 Therefore, it is recommended to combine the two calls into one, preventing the creation of an empty figure.因此,建议将两个调用合二为一,防止创建空图。
About f'{mean[i, j]:.2g}'
:关于
f'{mean[i, j]:.2g}'
:
f
changes the string into a formatted string . f
将字符串更改为格式化字符串。{}
are of the form {value:format}
or just {value}
(getting a default format) and will be replaced by a formatted text. {}
中的部分采用{value:format}
或{value}
形式(获取默认格式),并将替换为格式化文本。.2g
means a "general" format with 2
significant digits..2g
表示具有2
有效数字的“通用”格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.