0

How to change the position and size of the labels of the ticks of the vertical color bar of a seaborn's heatmap?

I tried with the following code

ax.figure.axes[-1].yaxis.label.set_size(36)
ax.figure.axes[-1].yaxis.label.set_position((4, 1.0))

However, this does not work, i.e. the font size of the labels of the ticks of the colorbar remain in the same position with the same font size. I am also doing

colorbar = ax.collections[0].colorbar
colorbar.set_ticks([-0.667, 0, 0.667])


# I want these labels to be bigger and more to the right!!
colorbar.set_ticklabels(['-1', '0', '1']) 

With colorbar.set_ticks([-0.667, 0, 0.667]), I can change the vertical position of the ticks, but I also want the associated labels to be farther away from the tick themselves.

nbro
  • 15,395
  • 32
  • 113
  • 196

1 Answers1

0

The ticks of a colorbar are a bit confusing, as the positions need to be set via colorbar.set_ticks(), but when you want to change other parameters, you have to go back to the underlying axes. For vertical colorbars the y-axis is used.

This post shows a way to always have the colorbar the same height as the main plot. The colorbar needs to be created outside sns.heatmap.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import seaborn as sns

ax = sns.heatmap(np.random.uniform(-.6, .6, (6, 12)), cmap='inferno', vmin=-0.667, vmax=0.667, square=True, cbar=False)
divider = make_axes_locatable(ax) 
cax = divider.append_axes("right", size="5%", pad=0.1) 
cbar = plt.colorbar(ax.collections[0], cax=cax)
cbar.set_ticks([-0.667, 0, 0.667])
cbar.ax.set_yticklabels(['-1', '0', '1'], size=20)
cbar.ax.tick_params(axis='y', which='major', length=0, pad=15)
cbar.outline.set_edgecolor('black')
cbar.outline.set_linewidth(2)
plt.tight_layout()
plt.show()

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • For some reason, now I only see the 1 and 0 labels on the right of the colorbar, i.e. the command `cbar.set_ticks([-0.667, 0, 0.667])` is not working as expected, but before it was working. Do you know why something would cause this? – nbro Aug 12 '20 at 15:10
  • 1
    If the lowest value in the heatmap is larger than `-0.667`, that value will not be present in the colorbar. You can force the colormapping to be exactly between `-0.667` and `0.667` via the `vmin` and `vmax` parameters: `sns.heatmap(... vmin=-0.667, vmax=0.667)`. – JohanC Aug 12 '20 at 15:11
  • Thanks! That was the problem: I hadn't noticed I was setting `vmin` and `vmax`. Sorry if I annoy you, but have you ever experienced that the colorbar becomes taller/bigger than the heatmap if you set `square=True` (i.e. you force the heatmap to be squared)? Is there a way to ensure that the colorbar is always of the same height of the heatmap? – nbro Aug 12 '20 at 15:21
  • Thanks! That solved the other issue too! If I could, I would upvote this answer 3-4 times :D – nbro Aug 12 '20 at 16:23