Home > Software engineering >  Shrink and anchor matplotlib colorbar
Shrink and anchor matplotlib colorbar

Time:06-12

How do I use colorbar attributes such as in this snippet:

import seaborn as sns

uniform_data = np.random.rand(10, 12) # random data
ax = sns.heatmap(uniform_data)

cbar = ax.collections[0].colorbar

plt.show()

To shrink the colorbar and put it to the bottom and anchored to the lower left corner (that is, NOT centered)?

Something like this, but with the colorbar shrinked to, let's say 70% and anchored to the bottom left

enter image description here

I am unsure how to search for the methods as cbar.set_location() is not available.

CodePudding user response:

If you want infinite customizability, you need to go more low level than you will get with seaborn, which gives convenience, but can't have knobs for everything.

The most straightforward way to get what you want is to place the colorbar axes manually. Note that you will need to play with the y offset, which I set here to -0.2.

import matplotlib.pyplot as plt
import numpy as np

uniform_data = np.random.rand(10, 12) # random data
fig, ax = plt.subplots(layout='constrained')
pc = ax.imshow(uniform_data)
cbax = ax.inset_axes([0, -0.2, 0.7, 0.05], transform=ax.transAxes)
fig.colorbar(pc, ax=ax, cax=cbax, shrink=0.7, orientation='horizontal')
plt.show()

enter image description here

CodePudding user response:

You could create the colorbar via seaborn, extract its position, adapt it and set it again:

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

uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, cbar_kws={'orientation': 'horizontal'})

cax = ax.collections[0].colorbar.ax  # get the ax of the colorbar
pos = cax.get_position()  # get the original position
cax.set_position([pos.x0, pos.y0, pos.width * 0.6, pos.height])  # set a new position
cax.invert_xaxis() # invert the direction of the colorbar
plt.show()

change seaborn colorbar position

Note that you need cbar_kws={'orientation': 'horizontal'} for a horizontal colorbar that by default is aligned with the x-axis.

After using .set_position, something like plt.tight_layout() won't work anymore.

  • Related