简体   繁体   中英

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. 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. Therefore, it is recommended to combine the two calls into one, preventing the creation of an empty figure.

About f'{mean[i, j]:.2g}' :

  • The f changes the string into a formatted string .
  • The parts inside {} are of the form {value:format} or just {value} (getting a default format) and will be replaced by a formatted text.
  • The format specifications are part of a complete mini-language , where .2g means a "general" format with 2 significant digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM