50

I use a trick to draw a colorbar whose height matches the master axes. The code is like

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

ax = plt.subplot(111)
im = ax.imshow(np.arange(100).reshape((10,10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

This trick works good. However, since a new axis is appended, the current instance of the figure becomes cax - the appended axis. As a result, if one performs operations like

plt.text(0,0,'whatever')

the text will be drawn on cax instead of ax - the axis to which im belongs.

Meanwhile, gcf().axes shows both axes.

My question is: How to make the current axis instance (returned by gca()) the original axis to which im belongs.

Liang
  • 875
  • 1
  • 9
  • 12
  • I just found a quick work-around: simply specify the 'ax' argument in plt.text to be the original ax:plt.colorbar(im, cax=cax, ax=ax) – Liang Oct 28 '13 at 00:50
  • Try ``ax.text(0, 0, 'whatever')``. – fjarri Oct 28 '13 at 00:51
  • @Bogdan, yes, I understand that works. Still that is a break of workflow if you want to continue to use simple plt.text(). By the quick work-around I just posted in my own comment, the call plt.colorbar(im, cax=cax, ax=ax) actually reverts gca() to ax. This appears to be more convenient if I want to wrap a function to draw a colorbar with matching height. – Liang Oct 28 '13 at 00:55
  • 2
    Whatever works for you, I just offered a possible solution. I personally find it easier to use explicit states (e.g. ``fig = plt.figure(...)``, ``ax = fig.subplot(...)``, ``ax.text(...)`` and so on. – fjarri Oct 28 '13 at 01:00
  • 1
    I'm with @Bogdan. The state machine is doing just that behind the scenes ( http://stackoverflow.com/questions/14254379/how-can-i-attach-a-pyplot-function-to-a-figure-instance/14261698#14261698) and now you have to worry about the hidden state doing strange things to you. – tacaswell Oct 28 '13 at 02:40

1 Answers1

99

Use plt.sca(ax) to set the current axes, where ax is the Axes object you'd like to become active.

Aaron
  • 8,897
  • 1
  • 26
  • 38
Joe Kington
  • 258,645
  • 67
  • 583
  • 455