Change the labels of a colorbar from increasing to decreasing values
Asked Answered
E

3

13

I'd like to change the labels for the colorbar from increasing to decreasing values. When I try to do this via vmin and vmax I get the error message:

minvalue must be less than or equal to maxvalue

So, for example I'd like the colorbar to start at 20 on the left and go up to 15 on the right.

This is my code for the colorbar so far, but in this example the values go from 15 to 20 and I'd like to reverse that order:

cmap1 = mpl.cm.YlOrBr_r

norm1 = mpl.colors.Normalize(15,20)

cb1   = mpl.colorbar.ColorbarBase(colorbar1, cmap=cmap1, norm=norm1, orientation='horizontal')

cb1.set_label('magnitude')
Excitant answered 30/5, 2013 at 1:57 Comment(0)
L
19

The colorbars displayed below are probably not exactly like yours, as they are just example colorbars to function as a proof of concept.

In the following I assume you have a colorbar similar to this, with increasing values to the right:

Original colorbar

Method 1: Inverting the x-axis

Inverts the whole x-axis of the colorbar

If you want to invert the x-axis, meaning that the values on the x-axis are descending to the right, making the colorbar "mirrored", you can make use of the ColorbarBase's ax attribute:

cb1   = mpl.colorbar.ColorbarBase(colorbar1,
                                  cmap=cmap1,
                                  norm=norm1,
                                  orientation='horizontal')
cb1.ax.invert_xaxis()

This gives.the output below.

Colorbar with inverted x-axis

It is also possible to change the number of ticklabels by setting the colorbars locator. Here the MultipleLocator is used, although you can use many other locators as well.

from matplotlib.ticker import MultipleLocator

cb1.locator = MultipleLocator(1) # Show ticks only for each multiple of 1
cb1.update_ticks()
cb1.ax.invert_xaxis() 

Colorbar with inverted x-axis and MultipleLocator

Method 2: Using custom ticklabels

Reverses the order of the ticklabels, keeping the orientation of the colorbar

If you want the orientation of the colorbar itself as it is, and only reverse the order in which the ticklabels appear, you can use the set_ticks and set_ticklabels methods. This is more of a "brute force" approach than the previous solution.

cb1.set_ticks(np.arange(15, 21))
cb1.set_ticklabels(np.arange(20, 14, -1))

This gives the colorbar seen below. Note that the colors are kept intact, only the tick locations and ticklabels have changed.

Colorbar with custom ticklabels

Lulualaba answered 30/5, 2013 at 1:57 Comment(0)
C
0

An alternative solution for producing the colorbar in Method 2:

cmap1 = cmap1.reversed()
cb1.ax.invert_yaxis()
Cyna answered 16/11, 2021 at 16:31 Comment(0)
C
0

works for me: variable_you_want.ax.invert_yaxis()

Creamcolored answered 1/2, 2023 at 21:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.