Olaf
Olaf

Reputation: 41

How to set a legend in an image heatmap (python)?

How can I move the vertical legend slightly upwards (to the centre of rows)? I need these very large letters

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np


labels_raw=np.array([["98.75\n±0.50"  ,"1.25\n±0.82"],[ "1.32\n±0.74", "98.68\n±0.74"]])
cm_raw=np.array([[98.75  ,1.25],[ 1.32, 98.68]])

sns.set(font_scale=2.5)


labels=labels_raw
cm=cm_raw


fig, ax = plt.subplots(figsize=(5,5))

target_names = ['test1','test2'] 


f=sns.heatmap(cm, annot=labels, fmt=':^', xticklabels=target_names, 
          yticklabels=target_names,annot_kws={"size": 25},cbar=False)
plt.show(block=False)  
#plt.show()
fig=f.get_figure()

output

Upvotes: 1

Views: 128

Answers (1)

StupidWolf
StupidWolf

Reputation: 46938

You can rotate your labels and set the vertical alignment to be center:

fig, ax = plt.subplots(figsize=(5,5))

target_names = ['test1','test2'] 

sns.heatmap(cm, annot=labels, fmt=':^', xticklabels=target_names, 
          yticklabels=target_names,annot_kws={"size": 25},cbar=False,ax=ax)

ax.set_yticklabels(target_names, rotation=0, fontsize="25", va="center")

enter image description here

Or this will keep the y-axis labels vertical:

sns.heatmap(cm, annot=labels, fmt=':^', xticklabels=target_names, 
          yticklabels=target_names,annot_kws={"size": 25},cbar=False,ax=ax)

ax.set_yticklabels(target_names, fontsize="25", va="center")

enter image description here

Upvotes: 1

Related Questions