如何修改Python代码实现Mandelbrot分形的单图缩放效果?
如何在单张图内实现Mandelbrot分形的自缩放效果?
我的Python代码生成了两张独立的Mandelbrot分形图像,而非在同一图像中实现缩放效果。请问该如何修改代码,使分形在单图内完成自缩放?
要在单张图内同时展示Mandelbrot分形的整体视图和局部放大效果,可以利用matplotlib的嵌入子图(inset_axes)功能。核心思路是先绘制完整的分形图,再在图中嵌入一个小坐标轴展示放大后的局部区域,同时添加标记框明确放大区域的位置。
修改后的完整代码如下:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes, mark_inset def testpoint(c, maxreps): z = 0 reps = 0 while abs(z) < 2 and reps < maxreps: z = z ** 2 + c reps += 1 frac = float(reps) / float(maxreps) return frac def compute_mandelbrot(N_max, xmin, xmax, ymin, ymax, nx, ny): # 生成c值网格 x = np.linspace(xmin, xmax, nx) y = np.linspace(ymax, ymin, ny) z = np.zeros([nx, ny]) for a in range(nx): for b in range(ny): z[a, b] = testpoint(complex(x[a], y[b]), N_max) return z if __name__ == '__main__': # 整体视图参数 full_xmin, full_xmax = -1.5, 0.5 full_ymin, full_ymax = -1, 1 pts = 800 # 计算整体分形 mandelbrot_full = compute_mandelbrot(50, full_xmin, full_xmax, full_ymin, full_ymax, pts, pts) # 创建画布和主坐标轴 fig, ax = plt.subplots(figsize=(8, 8)) # 绘制整体分形 im_full = ax.imshow(mandelbrot_full.T, extent=[full_xmin, full_xmax, full_ymin, full_ymax], cmap=plt.cm.rainbow) ax.set_title("Mandelbrot 分形(含局部放大)") plt.colorbar(im_full, ax=ax) # 局部放大区域参数 zoom_xmin, zoom_xmax = -1.0, 0.1 zoom_ymin, zoom_ymax = -0.5, 0.2 # 计算放大后的分形 mandelbrot_zoom = compute_mandelbrot(50, zoom_xmin, zoom_xmax, zoom_ymin, zoom_ymax, pts, pts) # 创建嵌入子坐标轴(位置和大小可调整) ax_inset = inset_axes(ax, width="30%", height="30%", loc="upper left", borderpad=1) # 绘制放大后的分形 ax_inset.imshow(mandelbrot_zoom.T, extent=[zoom_xmin, zoom_xmax, zoom_ymin, zoom_ymax], cmap=plt.cm.rainbow) ax_inset.set_title("局部放大") # 隐藏子轴的刻度,让图更简洁 ax_inset.set_xticks([]) ax_inset.set_yticks([]) # 标记放大区域在整体图中的位置 mark_inset(ax, ax_inset, loc1=2, loc2=4, fc="none", ec="black") plt.show()
关键修改点:
- 引入
inset_axes和mark_inset工具,实现嵌入子图和放大区域标记 - 将两次绘图操作合并到同一个画布中,不再单独调用
plt.show()两次 - 调整绘图逻辑,先绘制整体视图,再在嵌入子轴中绘制放大后的局部视图
- 可通过修改
inset_axes的参数(width、height、loc)调整放大窗口的大小和位置
内容的提问来源于stack exchange,提问作者Olivia
相关产品推荐
相关产品推荐

