我目前正在使用matplotlib编写Mandelbrot集合的代码,该集合带有zoom 功能,可以无限放大其中的任何部分,然而,当我放大新数据时,计算得到的数据偏离图轴的中心.

enter image description here

这个屏幕截图显示了一次放大后的图形--没有正确地为轴生成集合.图形应该是关于y=0的对称的,但它不是-每当我zoom 时它都会改变.我想不出这可能是什么原因--我在代码中看不到任何问题.我该怎么解决这个问题?

以下是我的代码:

import numpy as np
import matplotlib.pyplot as plt

def mandelbrot_set(xmin, xmax, ymin, ymax, width, height, maxiter):
    x = np.linspace(xmin, xmax, width).reshape((1, width))
    y = np.linspace(ymin, ymax, height).reshape((height, 1))
    c = x + y * 1j
    z = c
    fractal = np.zeros(z.shape, dtype=int)
    for i in range(maxiter):
        z = z**2 + c
        mask = np.abs(z) > 2
        fractal += mask
        z[mask] = 2
    return fractal

xmin, xmax, ymin, ymax = -2, 1, -1.5, 1.5
maxiter = 300
width, height = 500, 500

fractal = mandelbrot_set(xmin, xmax, ymin, ymax, width, height, maxiter)
fig, ax = plt.subplots(figsize=(10, 10))
im = ax.imshow(fractal, cmap='magma', extent=(xmin, xmax, ymin, ymax))


def update_plot(xmin, xmax, ymin, ymax):
    fractal = mandelbrot_set(xmin, xmax, ymin, ymax, width, height, maxiter)
    im.set_data(fractal)
    im.set_extent((xmin, xmax, ymin, ymax))
    fig.canvas.draw()

def on_scroll(event):
    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()

    x, y = event.xdata, event.ydata
    if event.button == 'up':
        scale_factor = 0.5
    else:
        scale_factor = 2.0
    xmin = x - (x - xmin)*scale_factor
    xmax = x + (xmax - x)*scale_factor
    ymin = y - (y - ymin)*scale_factor
    ymax = y + (ymax - y)*scale_factor
    print(f"xmin: {xmin}, xmax: {xmax}, ymin: {ymin}, ymax: {ymax}")

    update_plot(xmin, xmax, ymin, ymax)

fig.canvas.mpl_connect('scroll_event', on_scroll)

plt.show()

推荐答案

您的问题是,imshow默认情况下绘制带有origin='upper'(https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow)的地块,这意味着Y轴被反转,从而 destruct 了下游的边界计算,使用

im = ax.imshow(fractal, cmap='magma', extent=(xmin, xmax, ymin, ymax), origin='lower')

它会解决你的问题.

我也不确定这是否是你方故意的,但这个边界更新规则似乎更有意义?

xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
x_scale = xmax - xmin
y_scale = ymax - ymin
dx = x_scale/2*scale_factor
dy = y_scale/2*scale_factor
xmin = x - dx
xmax = x + dx
ymin = y - dy
ymax = y + dy

Python相关问答推荐

如何使用bs 4从元素中提取文本

NumPy中的右矩阵划分,还有比NP.linalg.inv()更好的方法吗?

具有症状的分段函数:如何仅针对某些输入值定义函数?

如何将ctyles.POINTER(ctyles.c_float)转换为int?

Pandas实际上如何对基于自定义的索引(integer和非integer)执行索引

pandas滚动和窗口中有效观察的最大数量

Mistral模型为不同的输入文本生成相同的嵌入

如何获取TFIDF Transformer中的值?

用Python解密Java加密文件

如何列举Pandigital Prime Set

为什么默认情况下所有Python类都是可调用的?

创建可序列化数据模型的最佳方法

如何并行化/加速并行numba代码?

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

如何保持服务器发送的事件连接活动?

UNIQUE约束失败:customuser. username

Flash只从html表单中获取一个值

Flask Jinja2如果语句总是计算为false&

并行编程:同步进程

Regex用于匹配Python中逗号分隔的AWS区域