Title: Matplotlib: Is there a way to get a colorbar axis from a parent axis?
Tags: python;matplotlib;data-visualization;visualization;colorbar
Question: 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
&gt;&gt;&gt; [<AxesSubplot:&gt;, <AxesSubplot:label='<colorbar&gt;'&gt;]
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)?

Here is the accepted answer: 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()
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.
Comment for this answer: Thanks for the response. I was aware of that possibility but was looking for the specific solution of obtaining the colorbar axis in a bigger context
Comment for this answer: Thanks again. While using ```ax.figure.axes[1]``` works for the simple cases. It is likely to fail for more complex subplot layouts. So there no general solution to the problem except for manually keeping track of both axis.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:08/31/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><matplotlib><data-visualization><visualization><colorbar>', 'Title': 'Matplotlib: Is there a way to get a colorbar axis from a parent axis?', 'ViewCount': 330, 'id': 68999470, 'user_AboutMe': None, 'user_AccountId': 19466805.0, 'user_DisplayName': 'fabian', 'user_Reputation': 53.0, 'user_Views': 11.0, 'user_id': 14239944.0}}