3

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?

Community
  • 1
  • 1
Manila Thrilla
  • 547
  • 1
  • 8
  • 17

2 Answers2

5

@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:

Manila Thrilla
  • 547
  • 1
  • 8
  • 17
2

the plt.colorbar() is made for really simple cases, e.g. not really thought for a plot with 2 y-axes. For a fine grained control of the colorbar location and properties you should almost always rather work with colorbar specifying on which axes you want to plot the colorbar.

# on the figure total in precent l    b      w , height 
cbaxes = fig.add_axes([0.1, 0.1, 0.8, 0.05]) # setup colorbar axes. 
# put the colorbar on new axes
cbar = fig.colorbar(mapable,cax=cbaxes,orientation='horizontal')

Note that colorbar takes the following keywords:

keyword arguments:

cax None | axes object into which the colorbar will be drawn ax None | parent axes object from which space for a new colorbar axes will be stolen

you could also see here a more extended answer of mine regarding figure colorbar on separate axes.

Community
  • 1
  • 1
oz123
  • 27,559
  • 27
  • 125
  • 187