Matplotlib colorbar ticks on left/opposite side
Asked Answered
I

4

28

One could generate a vertical colorbar like so(simplified):

import matplotlib.pyplot as plt
import matplotlib as mpl

plt.figure()
c_ax=plt.subplot(111)
cb = mpl.colorbar.ColorbarBase(c_ax,orientation='vertical')
plt.savefig('my_colorbar.png')

Resulting in something like this(rotated for space reasons):enter image description here

Is it possible to get the ticks labels on the opposite side?

Ileum answered 29/4, 2016 at 13:1 Comment(0)
P
49

You can switch the position of the ticks using c_ax.yaxis.set_ticks_position()

So for your example:

import matplotlib.pyplot as plt
import matplotlib as mpl

plt.viridis()

fig=plt.figure()
c_ax=plt.subplot(199)

cb = mpl.colorbar.ColorbarBase(c_ax,orientation='vertical')

c_ax.yaxis.set_ticks_position('left')

plt.savefig('my_colorbar.png')

enter image description here

Note you can also move the colorbar label in a similar way:

c_ax.yaxis.set_label_position('left')

And finally, in case you have a horizontal colorbar, and want to move the ticks and labels to the top, you can use the equivalent function on the xaxis:

c_ax.xaxis.set_label_position('top')
c_ax.xaxis.set_ticks_position('top')
Pleading answered 29/4, 2016 at 13:24 Comment(0)
G
6

For some reason applying changes to the colorbar input axes (cax parameter) did not work for me.

However, grabbing the axes from the colorbar object and then applying the changes worked nicely:

cb.ax.xaxis.set_ticks_position("top")
Greggrega answered 26/11, 2020 at 0:8 Comment(0)
D
1

I was having the same problem. This situation probably arises when you are setting explicitly the axes of the colorbar. In that case you can easily specify on what side of these axes you get the the ticks and the labels. For example, if you have created an image using imshow

fig = plt.figure()
ax = plt.subplot(1, 1, 1)
im = ax.imshow(data)

You can define the axis for the colorbar, in this example using inset_axes:

from mpl_toolkits.axes_grid1.inset_locator import inset_axes
cbaxes = inset_axes(ax, width="7%", height="20%", loc=4)

then add your colorbar

cb = fig.colorbar(im, cax=cbaxes, ticks=[vmin, vmax], orientation='vertical')

and then control the position of the ticks, etc...

cbaxes.yaxis.tick_left()
Defence answered 26/11, 2019 at 20:25 Comment(0)
P
1

I don't know why, but none of these commands worked for me. If that's also your case, I solved the issue by specifying the colorbar property

location='left'

which takes care of both the ticks and the label. If you still want the colorbar to be on the right side of the plot, just define a new axis limited to the position you want and link you colorbar to it.

cbar_ax=fig.add_axes([x0, y0, width, height])
Ponder answered 25/5, 2020 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.