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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With