Viewlims

创建两个相同的面板。在右侧面板上放大将在第一个面板中显示一个矩形,表示缩放的区域。

Viewlims

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.patches import Rectangle
  4. # We just subclass Rectangle so that it can be called with an Axes
  5. # instance, causing the rectangle to update its shape to match the
  6. # bounds of the Axes
  7. class UpdatingRect(Rectangle):
  8. def __call__(self, ax):
  9. self.set_bounds(*ax.viewLim.bounds)
  10. ax.figure.canvas.draw_idle()
  11. # A class that will regenerate a fractal set as we zoom in, so that you
  12. # can actually see the increasing detail. A box in the left panel will show
  13. # the area to which we are zoomed.
  14. class MandelbrotDisplay(object):
  15. def __init__(self, h=500, w=500, niter=50, radius=2., power=2):
  16. self.height = h
  17. self.width = w
  18. self.niter = niter
  19. self.radius = radius
  20. self.power = power
  21. def __call__(self, xstart, xend, ystart, yend):
  22. self.x = np.linspace(xstart, xend, self.width)
  23. self.y = np.linspace(ystart, yend, self.height).reshape(-1, 1)
  24. c = self.x + 1.0j * self.y
  25. threshold_time = np.zeros((self.height, self.width))
  26. z = np.zeros(threshold_time.shape, dtype=complex)
  27. mask = np.ones(threshold_time.shape, dtype=bool)
  28. for i in range(self.niter):
  29. z[mask] = z[mask]**self.power + c[mask]
  30. mask = (np.abs(z) < self.radius)
  31. threshold_time += mask
  32. return threshold_time
  33. def ax_update(self, ax):
  34. ax.set_autoscale_on(False) # Otherwise, infinite loop
  35. # Get the number of points from the number of pixels in the window
  36. dims = ax.patch.get_window_extent().bounds
  37. self.width = int(dims[2] + 0.5)
  38. self.height = int(dims[2] + 0.5)
  39. # Get the range for the new area
  40. xstart, ystart, xdelta, ydelta = ax.viewLim.bounds
  41. xend = xstart + xdelta
  42. yend = ystart + ydelta
  43. # Update the image object with our new data and extent
  44. im = ax.images[-1]
  45. im.set_data(self.__call__(xstart, xend, ystart, yend))
  46. im.set_extent((xstart, xend, ystart, yend))
  47. ax.figure.canvas.draw_idle()
  48. md = MandelbrotDisplay()
  49. Z = md(-2., 0.5, -1.25, 1.25)
  50. fig1, (ax1, ax2) = plt.subplots(1, 2)
  51. ax1.imshow(Z, origin='lower', extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max()))
  52. ax2.imshow(Z, origin='lower', extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max()))
  53. rect = UpdatingRect([0, 0], 0, 0, facecolor='None', edgecolor='black', linewidth=1.0)
  54. rect.set_bounds(*ax2.viewLim.bounds)
  55. ax1.add_patch(rect)
  56. # Connect for changing the view limits
  57. ax2.callbacks.connect('xlim_changed', rect)
  58. ax2.callbacks.connect('ylim_changed', rect)
  59. ax2.callbacks.connect('xlim_changed', md.ax_update)
  60. ax2.callbacks.connect('ylim_changed', md.ax_update)
  61. ax2.set_title("Zoom here")
  62. plt.show()

下载这个示例