【问题标题】:matplotlib: change the current axis instance (i.e., gca())matplotlib:更改当前轴实例(即 gca())
【发布时间】:2013-11-06 16:19:39
【问题描述】:

我对@9​​87654321@ 使用了一个技巧。代码是这样的

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().axes 显示两个轴。

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

【问题讨论】:

  • 我刚刚找到了一个快速解决方法:只需将 plt.text 中的 'ax' 参数指定为原始 ax:plt.colorbar(im, cax=cax, ax=ax)跨度>
  • 试试ax.text(0, 0, 'whatever')
  • @Bogdan,是的,我知道这行得通。如果您想继续使用简单的 plt.text(),这仍然是工作流程的中断。通过我刚刚在自己的评论中发布的快速解决方法,调用 plt.colorbar(im, cax=cax, ax=ax) 实际上将 gca() 恢复为 ax。如果我想包装一个函数来绘制一个高度匹配的颜色条,这似乎更方便。
  • 不管对你有用,我只是提供了一个可能的解决方案。我个人觉得使用显式状态更容易(例如fig = plt.figure(...)ax = fig.subplot(...)ax.text(...) 等等。
  • 我和@Bogdan 在一起。状态机在幕后 (stackoverflow.com/questions/14254379/…) 就是这样做的,现在你不得不担心隐藏状态会对你做奇怪的事情。

标签: python python-2.7 matplotlib


【解决方案1】:

使用plt.sca(ax) 设置当前坐标区,其中ax 是您想要激活的Axes 对象。

【讨论】:

  • 具体来说,plt.sca(ax),带ax就是你想成为当前轴的轴的名字。
猜你喜欢
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
相关资源
最近更新 更多