Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve all colorbars in figure

I'm trying to manipulate all colorbar instances contained in a figure. There is fig.get_axes() to obtain a list of axes, but I cannot find anything similar for colorbars.

This answer, https://stackoverflow.com/a/19817573/7042795, only applies to special situations, but not the general case.

Consider this MWE:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.random((10,10)) # Generate some random data to plot

fig, axs = plt.subplots(1,2)

im1 = axs[0].imshow(data)    
cbar1 = fig.colorbar(im1)

im2 = axs[1].imshow(2*data)    
cbar2 = fig.colorbar(im2)

fig.show()

How can I get cbar1 and cbar2 from fig?

What I need is a function like:

def get_colorbars(fig):
  cbars = fig.get_colorbars()
  return cbars

cbars = get_colorbars(fig)
like image 564
Bastian Avatar asked Dec 14 '25 05:12

Bastian


1 Answers

You would have no choice but to check each object present in the figure whether it has a colorbar or not. This could look as follows:

def get_colorbars(fig):
    cbs = []
    for ax in fig.axes:
        cbs.extend(ax.findobj(lambda obj: hasattr(obj, "colorbar") and obj.colorbar))
    return [a.colorbar for a in cbs]

This will give you all the colorbars that are tied to an artist. There may be more colorbars in the figure though, e.g. created directly from a ScalarMappble or multiple colorbars for the same object; those cannot be found.

like image 169
ImportanceOfBeingErnest Avatar answered Dec 16 '25 18:12

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!