2015-04-23 107 views
2

我发现Matplotlib库可以动画他们的图纸并处理事件 - 就像鼠标点击一样。我需要使易于交互式Mandelbrot集缩放代码。出于显而易见的原因,我无法以无限的精度把它画出来;)我认为,在用户缩放之后,可能会出现新的边界,并在新边界中绘制Mandelbrot的一部分,并具有足够的新的精度。Python matplotlib - 再放大缩小

有没有简单的方法来做到这一点?或者只是一种方式? :)

回答

2

查看event-handling功能,为此提供了一个简单示例here

在上面链接的示例中,您只需在“onpress”(连接到鼠标事件)的函数中添加自己的重新计算代码。类似下面的工作对我来说:

import matplotlib.pyplot as plt 
import numpy as np 

class ZoomPlot(): 

    def __init__(self): 
     self.fig = plt.figure() 
     self.ax = self.fig.add_subplot(111) 
     self.xmin = -2.5; self.xmax = 1.0; 
     self.ymin = -1.5; self.ymax = 1.5; 
     self.xpress = self.xmin 
     self.xrelease = self.xmax 
     self.ypress = self.ymin 
     self.yrelease = self.ymax 
     self.resolution = 200 
     self.maxiters = 30 

     self.fig.canvas.mpl_connect('button_press_event', self.onpress) 
     self.fig.canvas.mpl_connect('button_release_event', self.onrelease) 
     self.plot_fixed_resolution(self.xmin, self.xmax, 
            self.ymin, self.ymax) 

    def mandlebrot(self, X, Y): 
     C = X + Y*1j 
     Z = C 
     divtime = self.maxiters + np.zeros(Z.shape, dtype=int) 
     for n in range(self.maxiters): 
      Z = Z**2 + C 
      diverge = Z*np.conj(Z) > 2**2 
      div_now = diverge & (divtime == self.maxiters) 
      divtime[div_now] = n 
      Z[diverge] = 2 

     return divtime 

    def plot_fixed_resolution(self, x1, x2, y1, y2): 
     x = np.linspace(x1, x2, self.resolution) 
     y = np.linspace(y1, y2, self.resolution) 
     X, Y = np.meshgrid(x, y) 
     C = self.mandlebrot(X, Y) 
     self.ax.clear() 
     self.ax.set_xlim(x1, x2) 
     self.ax.set_ylim(y1, y2) 
     self.ax.pcolormesh(X, Y, C) 
     self.fig.canvas.draw() 

    def onpress(self, event): 
     if event.button != 1: return 
     self.xpress = event.xdata 
     self.ypress = event.ydata 

    def onrelease(self, event): 
     if event.button != 1: return 
     self.xrelease = event.xdata 
     self.yrelease = event.ydata 
     self.xmin = min(self.xpress, self.xrelease) 
     self.xmax = max(self.xpress, self.xrelease) 
     self.ymin = min(self.ypress, self.yrelease) 
     self.ymax = max(self.ypress, self.yrelease) 
     self.plot_fixed_resolution(self.xmin, self.xmax, 
            self.ymin, self.ymax) 


plot = ZoomPlot() 
plt.show() 
+0

我不知道我是否应该接受这个作为一个答案,但由于:) –

+0

@CheshireCat非常欢迎。你缺少什么?我能澄清的任何事情? –

+0

现在我正在尝试使用此代码来生成我的Mandelbrot集示例。如果我这样做不好,张贴它,你会得到我的接受:) –