Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw colorbar with twin scales

I'd like to draw a (vertical) colorbar, which has two different scales (corresponding to two different units for the same quantity) on each side. Think Fahrenheit on one side and Celsius on the other side. Obviously, I'd need to specify the ticks for each side individually.

Any idea how I can do this?

like image 236
andreas-h Avatar asked Nov 26 '14 14:11

andreas-h


People also ask

How do you make a color bar?

Basic continuous colorbar Set the colormap and norm to correspond to the data for which the colorbar will be used. Then create the colorbar by calling ColorbarBase and specify axis, colormap, norm and orientation as parameters. Here we create a basic continuous colorbar with ticks and labels.

What is Colorbar mappable?

A colorbar needs a "mappable" ( matplotlib. cm. ScalarMappable ) object (typically, an image) which indicates the colormap and the norm to be used. In order to create a colorbar without an attached image, one can instead use a ScalarMappable with no associated data.


2 Answers

That should get you started:

import matplotlib.pyplot as plt
import numpy as np

# generate random data
x = np.random.randint(0,200,(10,10))
plt.pcolormesh(x)

# create the colorbar
# the aspect of the colorbar is set to 'equal', we have to set it to 'auto',
# otherwise twinx() will do weird stuff.
cbar = plt.colorbar()
pos = cbar.ax.get_position()
cbar.ax.set_aspect('auto')

# create a second axes instance and set the limits you need
ax2 = cbar.ax.twinx()
ax2.set_ylim([-2,1])

# resize the colorbar (otherwise it overlays the plot)
pos.x0 +=0.05
cbar.ax.set_position(pos)
ax2.set_position(pos)

plt.show()

enter image description here

like image 107
hitzg Avatar answered Sep 28 '22 08:09

hitzg


If you create a subplot for the colorbar, you can create a twin axes for that subplot and manipulate it like a normal axes.

import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1,2.7)
X,Y = np.meshgrid(x,x)
Z = np.exp(-X**2-Y**2)*.9+0.1

fig, (ax, cax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[15,1]})

im =ax.imshow(Z, vmin=0.1, vmax=1)
cbar = plt.colorbar(im, cax=cax)
cax2 = cax.twinx()

ticks=np.arange(0.1,1.1,0.1)
iticks=1./np.array([10,3,2,1.5,1])
cbar.set_ticks(ticks)
cbar.set_label("z")
cbar.ax.yaxis.set_label_position("left")
cax2.set_ylim(0.1,1)
cax2.set_yticks(iticks)
cax2.set_yticklabels(1./iticks)
cax2.set_ylabel("1/z")

plt.show()

enter image description here

like image 22
ImportanceOfBeingErnest Avatar answered Sep 28 '22 10:09

ImportanceOfBeingErnest