Is it possible to annotate imshow heatmap the way that if the value from pandas Dataframe is e.g. less than 3, then make mark “x” in that specific heatmap window?
Lets assume I have similar data to this example:
JavaScript
x
9
1
d = {'col1': [1,2,1,5,3], 'col2': [3,4,1,5,2],'col3': [3,4,3,1,2],'col4': [3,4,1,2,5]}
2
df = pd.DataFrame(data=d)
3
4
fig = plt.figure(figsize=(6,4))
5
plot = plt.imshow(df)
6
ax = plot.axes
7
ax.invert_yaxis()
8
ax.set_xticklabels(df.columns)
9
I saw that we can annotate all heatmap windows with corresponding values, however I can’t figure out how to annotate just the windows below my given limit and not with the corresponding value but e.g. with mark “x”. Can I ask for suggestions if it is possible with matplotlib heatmaps, please? Thank you.
Advertisement
Answer
- Iterate through the values, and use an
if-condition
to control adding the text. - Modified from how to annotate heatmap with text in matplotlib
JavaScript
1
18
18
1
d = {'col1': [1,2,1,5,3], 'col2': [3,4,1,5,2],'col3': [3,4,3,1,2],'col4': [3,4,1,2,5]}
2
df = pd.DataFrame(data=d)
3
4
fig = plt.figure(figsize=(7, 7))
5
plot = plt.imshow(df)
6
ax = plot.axes
7
ax.invert_yaxis()
8
ax.set_xticks(range(len(df.columns)), df.columns)
9
10
for y in range(df.shape[0]):
11
for x in range(df.shape[1]):
12
val = df.iloc[y, x]
13
if val >= 3:
14
val = 'x'
15
plt.text(x, y, val, fontsize=14,
16
horizontalalignment='center',
17
verticalalignment='center')
18