Rotate colorbar shortcut shortcuts in matplotlib

I would like to rotate the labels of the colorbar labels so that they are read vertically, not horizontally. I tried as many variations as I can think of with cbar.ax.set_xticklabels and cbar.ax.ticklabel_format etc. Using rotation='vertical' , but not yet landed.

I have provided 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() 

Image example

Any pointers would be greatly appreciated - I'm sure it should be pretty simple ...

+4
source share
2 answers

You can use cbar.ax.set_xticklabels to change the rotation (or set_yicklabels if you have a vertical color bar).

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

enter image description here

EDIT:

To set ticks correctly, you can search where clevs1 should be used in your clevs1 array, and use it 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

+5
source

If you are happy with tag locations and shortcuts and just want to rotate them:

 cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), rotation='vertical') 
+3
source

All Articles