Draw second colorbar axis outside of first axis


The result is:
Draw second colorbar axis outside of first axis

This code shows how to draw second colorbar axis outside of first colorbar axis.

See also:

Python Matplotlib Tips: Add second x-axis below first x-axis using Python and matplotlib.pyplot

This page shows how to draw second x-axis below the first x-axis. Using "twinx", "set_ticks_position", and "set_label_position", and "spines['bottom'].set_position", you can move the second x-axis from the top of the figure to below the first x-axis.


This code is refferring the following web page:

In [1]:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
In [2]:
plt.figure(facecolor='w',figsize=(5,4))
# generate random data
x = np.random.randint(0,200,(11,11))
dmin,dmax = 0,200
plt.imshow(x,vmin=dmin,vmax=dmax)

# 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.
# ref: Draw colorbar with twin scales - stack overflow -
# URL: https://stackoverflow.com/questions/27151098/draw-colorbar-with-twin-scales
cbar = plt.colorbar()
pos = cbar.ax.get_position()
ax1 = cbar.ax
ax1.set_aspect('auto')

# create a second axis and specify ticks based on the relation between the first axis and second aces
ax2 = ax1.twinx()
ax2.set_ylim([dmin,dmax])
newlabel = [273.15,310,350,390,430,473.15] # labels of the ticklabels: the position in the new axis
k2degc = lambda t: t-273.15 # convert function: from Kelvin to Degree Celsius
newpos   = [k2degc(t) for t in newlabel]   # position of the ticklabels in the old axis
ax2.set_yticks(newpos)
ax2.set_yticklabels(newlabel)

# resize the colorbar
pos.x1 -= 0.08

# arrange and adjust the position of each axis, ticks, and ticklabels
ax1.set_position(pos)
ax2.set_position(pos)
ax1.yaxis.set_ticks_position('right') # set the position of the first axis to right
ax1.yaxis.set_label_position('right') # set the position of the fitst axis to right
ax1.set_ylabel(u'Temperature [\u2103]')
ax2.yaxis.set_ticks_position('right') # set the position of the second axis to right
ax2.yaxis.set_label_position('right') # set the position of the second axis to right
ax2.spines['right'].set_position(('outward', 50)) # adjust the position of the second axis
ax2.set_ylabel('Temperature [K]')

# Save the figure
plt.savefig('two_color_ticks.png', bbox_inches='tight', pad_inches=0.02, dpi=150)