您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

matplotlib中的放大插图,无需重新绘制数据

matplotlib中的放大插图,无需重新绘制数据

我认为以下是您想要的。请注意,将返回的 手柄用于第一个手柄imshow,并将其添加到插入的轴上。您需要 制作一个副本,以便每个图都有单独的句柄,

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
import copy

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]
im = ax.imshow(Z2, extent=extent, interpolation="nearest",
          origin="lower")

#Without copy, image is shown in insert only
imcopy = copy.copy(im)
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.add_artist(imcopy)

# 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 b@R_642_2419@ of the region of the inset axes in the parent axes and
# connecting lines between the b@R_642_2419@ and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

plt.draw()
plt.show()

For your wrapper function, this would be something like,

def plot_with_zoom(*args, **kwargs):
    im = ax.imshow(*args, **kwargs)
    imcopy = copy.copy(im)
    axins.add_artist(imcopy)

但是,由于imshow只是将存储在数组中的数据显示Z为图像,所以我 认为这种解决方案实际上比对两个单独的调用要慢imshow。对于需要更多时间的地块,例如contour地块或pcolormesh,此方法可能是明智的……

编辑:

除了单个imshow,还包括多个不同类型的地块。绘图 函数都返回不同的句柄(例如plot返回行列表, imshow返回matplotlib.image.AxesImage等)。您可以 在绘制时继续将这些句柄添加到列表(或字典)中(如果它们 足够相似,则可以使用 集合 )。然后,您可以编写一个通用函数,该函数 使用缩放轴上的add_artist或add_patch方法将它们添加到轴上,可能使用 类型检查来处理绘图中使用的各种类型。一种更简单的 方法可能是遍历ax.get_children()并重用不是 轴本身元素的任何内容

一个选项可以是考虑块传输技术, 光栅化 使用或用于加速动画的其他技术,例如fig.canvas.copy_from_b@R_642_2419@fig.canvas.tostring_rgb在整个复制 图形作为图像(参见为什么与Matplotlib所以绘制 慢?低)。您还可以绘制图形,将其保存到非 矢量图形(使用savefigStringIO缓冲区或使用StringIO缓冲区),读回并绘制放大 的版本。

其他 2022/1/1 18:34:11 有529人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶