Python matplotlib:更改当前轴实例(即 gca())
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19625563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
matplotlib: change the current axis instance (i.e., gca())
提问by Liang
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
这个技巧效果很好。但是,由于附加了新轴,图形的当前实例变为 cax - 附加轴。因此,如果执行类似的操作
plt.text(0,0,'whatever')
the text will be drawn on cax instead of ax - the axis to which im belongs.
文本将绘制在 cax 而不是 ax - im 所属的轴上。
Meanwhile, gcf().axes shows both axes.
同时, gcf().axes 显示两个轴。
My question is: How to make the current axis instance (returned by gca()) the original axis to which im belongs.
我的问题是:如何使当前轴实例(由 gca() 返回)成为 im 所属的原始轴。
采纳答案by Joe Kington
Use plt.sca(ax)
to set the current axes, where ax
is the Axes
object you'd like to become active.
使用plt.sca(ax)
设置当前轴,其中ax
是Axes
你想成为活动对象。