matplotlib:更改当前轴实例(即gca())

Lia*_*ang 31 python matplotlib python-2.7

我用一个技巧来绘制一个高度与主轴相匹配的颜色条.代码就像

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)
Run Code Online (Sandbox Code Playgroud)

这个技巧很好用.但是,由于附加了新轴,因此图形的当前实例变为cax - 附加轴.结果,如果执行像这样的操作

plt.text(0,0,'whatever')
Run Code Online (Sandbox Code Playgroud)

文本将在cax而不是ax上绘制 - 我所属的轴.

同时,gcf().轴显示两个轴.

我的问题是:如何使当前轴实例(由gca()返回)成为im所属的原始轴.

Joe*_*ton 60

使用plt.sca(ax)设置当前轴,其中axAxes你想成为活动对象.

  • 具体来说,plt.sca(ax),其中 ax 是您希望成为当前轴的轴的名称。 (2认同)