Search code examples
pythonmatplotlibdata-visualizationvisualizationcolorbar

Matplotlib: Is there a way to get a colorbar axis from a parent axis?


I am doing a plot something like this:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

fig = plt.gcf()
ax = plt.gca()
ax.pcolormesh(np.random.rand(10, 10))
fig.colorbar(mpl.cm.ScalarMappable(), ax=ax)

The last line adds a colorbar and a second axis

fig.axes
>>> [<AxesSubplot:>, <AxesSubplot:label='<colorbar>'>]

My question: Is there any relation between the two axes that can be used to get the axis of the colorbar (second in the list above) using only the axis returned by ax = plt.gca() (first returned in the list above)?


Solution

  • As far as I know, if you define pcolormesh and colorbar that way, no.
    Anyway, you can define an ax for the pcolormesh and a cax for the colorbar beforehand. Then you can pass cax as parameter to matplotlib.pyplot.colorbar. In this way you can access to both axis ax and cax as you need.

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import numpy as np
    
    
    grid_kws = {'width_ratios': (0.9, 0.05), 'wspace': 0.2}
    fig, (ax, cax) = plt.subplots(1, 2, gridspec_kw = grid_kws, figsize = (10, 8))
    ax.pcolormesh(np.random.rand(10, 10))
    plt.colorbar(mpl.cm.ScalarMappable(), cax=cax)
    
    plt.show()
    

    enter image description here


    In general, focusing on your code:

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.gcf()
    ax = plt.gca()
    ax.pcolormesh(np.random.rand(10, 10))
    fig.colorbar(mpl.cm.ScalarMappable(), ax=ax)
    

    starting from ax, you can get its figure with ax.figure. From there, you can get the list of all figure axes with ax.figure.axes. So, if you want to get colobar's axis using only pcolormesh' axis, you should use:

    ax.figure.axes[1]
    

    The parent figure, as far as I know, is the only relation between the two axes.