Plot multiple y-axis AND colorbar in matplotlib

北慕城南 提交于 2020-06-26 04:25:06

问题


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:

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?


回答1:


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




回答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.



来源:https://stackoverflow.com/questions/10921316/plot-multiple-y-axis-and-colorbar-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!