I want to draw a seaborn.heatmap
and annotate only some rows/columns.
Example where all cells have annotation:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
n1 = 5
n2 = 10
M = np.random.random((n1, n2))
fig, ax = plt.subplots()
sns.heatmap(ax = ax, data = M, annot = True)
plt.show()
Following these examples (paragraph Adding Value Annotations), it is possible to pass to seaborn.heatmap
an array with annotations for each cell as annot
parameter:
annot : bool or rectangular dataset, optional
If True, write the data value in each cell. If an array-like with the same shape as data, then use this to annotate the heatmap instead of the data. Note that DataFrames will match on position, not index.
If I try to generate an array of str
and pass it as annot
parameter to seaborn.heatmap
I get the following error:
Traceback (most recent call last):
File "C:/.../myfile.py", line 16, in <module>
sns.heatmap(ax = ax, data = M, annot = A)
File "C:\venv\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "C:\venv\lib\site-packages\seaborn\matrix.py", line 558, in heatmap
plotter.plot(ax, cbar_ax, kwargs)
File "C:\venv\lib\site-packages\seaborn\matrix.py", line 353, in plot
self._annotate_heatmap(ax, mesh)
File "C:\venv\lib\site-packages\seaborn\matrix.py", line 262, in _annotate_heatmap
annotation = ("{:" + self.fmt + "}").format(val)
ValueError: Unknown format code 'g' for object of type 'numpy.str_'
Code which generates the ValueError
(in this case I try to remove annotations of the 4th columns as an example):
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
n1 = 5
n2 = 10
M = np.random.random((n1, n2))
A = np.array([[f'{M[i, j]:.2f}' for j in range(n2)] for i in range(n1)])
A[:, 3] = ''
fig, ax = plt.subplots(figsize = (6, 3))
sns.heatmap(ax = ax, data = M, annot = A)
plt.show()
What is the cause of this error?
How can I generate a seaborn.heatmap
and annotate only selected rows/columns?