change the colorbar width

Question:

enter image description here

I have created this, as you can see the colorbar is very thin, is there anyway of increasing the width of the colorbar without increasing the height

Asked By: John Smith

||

Answers:

You need to get hold of the axes of the colorbar.
Assuming you hold a reference to the colorbar in cbar you get to the axes via cbar.ax.

You can control the ratio of the height / width with ax.set_aspect(number). This will rescale the axes to match this ratio, but which way the rescaling is performed is not fully understood by me:

I might increase / decrease this number gradually in small steps and the axes would shrink / extent in one dimension to match the ratio accordingly. But at some point the behavior changes and further increase / decrease yields extension / shrinkage in the other dimension.

The documentation for axes.set_aspect says:

a circle will be stretched such that the height is num times the
width. aspect=1 is the same as aspect=’equal’

If you want to avoid this hassle completely you set ax.set_aspect('auto') and afterwards set the exact position of the axes explicitly with

ax.set_position((left, bottom, width, height))

The units are relative to the figure canvas and stretch from 0 to 1 with 0,0 being the bottom left corner of the canvas.

Example: set_position((0.1, 0.2, 0.4, 0.6)) will position the axes bottom left edge at (0.1, 0.2) and the top right edge at (0.1 + 0.4, 0.2 + 0.6)

Answered By: tzelleke

I was able to get the desired width of the colorbar using a combination of fraction and aspect parameters: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.colorbar.html

Answered By: Rob S
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.