Search code examples
pythonnumpymatplotlibcolorbar

Rotation of colorbar tick labels in matplotlib


I would like to rotate the colorbar tick labels so that they read vertically rather than horizontally. I have tried as many variations as I can think of with cbar.ax.set_xticklabels and cbar.ax.ticklabel_format and so on with rotation='vertical' but haven't quite landed it yet.

I've provided a MWE below:

import numpy as np
import matplotlib.pyplot as plt

#example function
x,y = np.meshgrid(np.linspace(-10,10,200),np.linspace(-10,10,200))
z = x*y*np.exp(-(x+y)**2)

#array for contourf levels
clevs = np.linspace(z.min(),z.max(),50)

#array for colorbar tick labels
clevs1 =np.arange(-200,100,10)

cs1 = plt.contourf(x,y,z,clevs)

cbar = plt.colorbar(cs1, orientation="horizontal")
cbar.set_ticks(clevs1[::1])

plt.show()

Example Image

Any pointers would be greatly appreciated - I'm sure this must be pretty simple...


Solution

  • You can use cbar.ax.set_xticklabels to change the rotation (or set_yicklabels if you had a vertical colorbar).

    cbar.ax.set_xticklabels(clevs1[::1],rotation=90)
    

    enter image description here

    EDIT:

    To set the ticks correctly, you can search for where in your clevs1 array the first tick should be using np.argmin, and use that to index clevs1 when you set_xticklabels:

    tick_start = np.argmin(abs(clevs1-clevs[0]))
    cbar.ax.set_xticklabels(clevs1[tick_start:],rotation=90)
    

    enter image description here