我正在处理一些 matplotlib 图,需要有一个缩放的插图。这是可能的zoomed_inset_axes
来自axes_grid1
工具包。参见示例here:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import numpy as np
def get_demo_image():
from matplotlib.cbook import get_sample_data
import numpy as np
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3,4,-4,3)
fig, ax = plt.subplots(figsize=[5,4])
# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z
# extent = [-3, 4, -4, 3]
ax.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()
这将给出所需的结果:
http://matplotlib.org/1.3.1/_images/inset_locator_demo21.png
但正如您在代码中看到的,数据必须绘制两次 - 一次用于主轴(ax.imshow...
) 一次用于插入轴 (axins.imshow...
).
我的问题是:
有没有办法添加缩放插图after主线剧情已经完成,without需要在新轴上再次绘制所有内容吗?
请注意:我并不是在寻找用函数包装绘图调用并让函数绘图的解决方案ax
and axins
(参见下面的示例),但是(如果存在)使用现有数据的本机解决方案ax
。有人知道这样的解决方案是否存在吗?
这是包装解决方案:
def plot_with_zoom(*args, **kwargs):
ax.imshow(*args, **kwargs)
axins.imshow(*args, **kwargs)
它有效,但感觉有点像黑客,因为如果我只想放大现有绘图的某个区域,为什么我需要再次绘制所有数据。
ed-smith 回答后的一些补充说明:
上面的例子当然只是最小的例子。图中可能有许多不同的数据集(并且数据集我的意思是通过绘制的东西imshow
or plot
ETC)。例如,想象一个包含 10 个点数组的散点图,所有点均与常见的 x 进行比较。
正如我上面所写,最直接的方法就是使用一个包装器来绘制所有实例中的数据。但我正在寻找一种从最终开始的方法(如果存在)ax
对象(而不是单个绘图命令)并以某种方式创建缩放插图。