Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python matplotlib:更改当前轴实例(即gca())_Python_Python 2.7_Matplotlib - Fatal编程技术网

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

Python matplotlib:更改当前轴实例(即gca()),python,python-2.7,matplotlib,Python,Python 2.7,Matplotlib,我用一个诡计来骗人。代码如下 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 c

我用一个诡计来骗人。代码如下

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)
这个把戏很管用。但是,由于附加了一个新轴,图形的当前实例将成为cax-附加轴。因此,如果执行以下操作:

plt.text(0,0,'whatever')
文本将绘制在cax上,而不是ax上——im所属的轴

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


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

用于设置当前轴,其中,
ax
是您希望激活的
axs
对象。

我刚刚找到了一个快速解决方法:只需在plt.text中指定'ax'参数为原始的ax:plt.colorbar(im,cax=cax,ax=ax)试试
ax.text(0,0,'which')
@Bogdan,是的,我理解这是可行的。如果您想继续使用simple plt.text(),这仍然是工作流的中断。通过我在自己的评论中发布的快速解决方法,调用plt.colorbar(im,cax=cax,ax=ax)实际上将gca()还原为ax。如果我想包装一个函数来绘制一个具有匹配高度的颜色条,这似乎更方便。无论对你有用什么,我只是提供了一个可能的解决方案。我个人觉得使用显式状态(例如,
fig=plt.figure(…)
ax=fig.subplot(…)
ax.text(…)
等等)更容易。我是@Bogdan。状态机只是在幕后做这些事情(),现在你不得不担心隐藏状态会给你带来奇怪的事情。特别是,plt.sca(ax),使用ax表示要作为当前轴的轴的名称。