Plot multiple y-axis AND colorbar in matplotlib

Manila Thrilla picture Manila Thrilla · Jun 6, 2012 · Viewed 7k times · Source

I am trying to produce a scatter plot that has two different y-axes and also a colorbar.

Here is the pseudo-code used:

#!/usr/bin/python

import matplotlib.pyplot as plt
from matplotlib import cm

fig = plt.figure()
ax1 = fig.add_subplot(111)
plt.scatter(xgrid,
        ygrid,
        c=be,                   # set colorbar to blaze efficiency
        cmap=cm.hot,
        vmin=0.0,
        vmax=1.0)

cbar = plt.colorbar()
cbar.set_label('Blaze Efficiency')

ax2 = ax1.twinx()
ax2.set_ylabel('Wavelength')

plt.show()

And it produces this plot: plot

My question is, how do you use a different scale for the "Wavelength" axes, and also, how do you move the colorbar more to right so that it is not in the Wavelength's way?

Answer

Manila Thrilla picture Manila Thrilla · Jun 25, 2012

@OZ123 Sorry that I took so long to respond. Matplotlib has extensible customizability, sometimes to the point where you get confused to what you are actually doing. Thanks for the help on creating separate axes.

However, I didn't think I needed that much control, and I ended up just using the PAD keyword argument in

fig.colorbar()

and this provided what I needed.

The pseudo-code then becomes this:

#!/usr/bin/python

import matplotlib.pyplot as plt
from matplotlib import cm

fig = plt.figure()
ax1 = fig.add_subplot(111)
mappable = ax1.scatter(xgrid,
                       ygrid,
                       c=be,                   # set colorbar to blaze efficiency
                       cmap=cm.hot,
                       vmin=0.0,
                       vmax=1.0)

cbar = fig.colorbar(mappable, pad=0.15)
cbar.set_label('Blaze Efficiency')

ax2 = ax1.twinx()
ax2.set_ylabel('Wavelength')

plt.show()

Here is to show what it looks like now:enter image description here: