Python交互绘制Julia集

matplotlib提供了交互操作的功能,比如,只要绑定button_press_event,就可以在点击图像时,触发相应的事件。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import time
def OnMouse(evt):
    x,y = evt.xdata, evt.ydata #xdata,ydata即当前坐标
    z = genZ([-2,2,-2,2],800,800)
    julia = getJulia(z,x+y*1j,40)
    jFig,jAx = plt.subplots()
    plt.imshow(julia, cmap=cm.jet)
    plt.gca().set_axis_off()
    plt.show()

# 用于生成Julia集
def getJulia(z,c,n,n0=0,m=2):
    t = time.time()
    c = np.zeros_like(z)+c
    out = abs(z)
    for i in range(n0,n0+n):
        absz = abs(z)
        z[absz>m]=0
        c[absz>m]=0
        out[absz>m]=i
        z = z*z + c
    print("time:",time.time()-t)
    return out

def genZ(axis,nx,ny):
    x0,x1,y0,y1 = axis
    x = np.linspace(x0,x1,nx)
    y = np.linspace(y0,y1,ny)
    real, img = np.meshgrid(x,y)
    z = real + img*1j
    return z

其中getJuliagetZ的解释可见python绘制动态Julia集,超炫酷

当然,众所周知,matplotlib中已经绑定了鼠标操作,故而首先要取消已经绑定的点击事件

def drawInter(img,axis):
    fig, ax = plt.subplots()
    plt.imshow(mBrot, cmap=cm.jet, extent=axis)
    plt.gca().set_axis_off()
    #取消链接点击事件
    fig.canvas.mpl_disconnect(
    	fig.canvas.manager.key_press_handler_id)
    #将点击和OnMouse链接起来
    fig.canvas.mpl_connect('button_press_event', OnMouse)
    plt.show()
n = 1000
axis = [-2,1,-1.5,1.5]
z = genZ(axis,1000,1000)
mBrot = getJulia(z,z,50)
drawInter(mBrot,axis)

这样,只要点击曼德勃罗集上的任意一点,就会绘制该点的Julia集。结果如图所示

Python交互绘制Julia集_第1张图片
此前曾经写过一个同名博客,但由于直接写到了类里面,所以有朋友吐槽代码太长

python交互绘制Julia集

你可能感兴趣的:(Python艺术,julia,微分方程,SciML)