曼德博集合(Mandelbrot Set)是一种复杂而美丽的数学分形,它可以通过迭代简单的数学规则来生成。在本教程中,我们将学习如何使用Python编程语言和Matplotlib库,在QT窗口中绘制曼德博集合,以及如何添加工具栏来调整大小、恢复视角和平移图像。
准备工作
确保你已经安装了matplotlib和PyQt5。如果没有,可以通过以下命令安装:
pip install matplotlib PyQt5
直接安装anaconda也可以,自带matplotlib和PyQt5,传送门:一步步教你:在QT窗口中展示Matplotlib绘图
编写代码
接下来,让我们编写代码来创建一个QT应用程序,该应用程序将绘制曼德博集合图像:
import sys
import numpy as np
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QVBoxLayout, QWidget, QToolBar, QAction
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar
class MandelbrotWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 创建一个matplotlib Figure
self.figure = plt.figure()
# 创建一个FigureCanvas实例,并将Figure传递给它
self.canvas = FigureCanvas(self.figure)
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
# 创建一个导航工具栏
self.toolbar = NavigationToolbar(self.canvas, self)
# 创建一个布局并将图形画布和工具栏添加到布局中
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# 创建一个QWidget作为主窗口的中心部件
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
# 设置窗口属性
self.setGeometry(100, 100, 800, 800)
self.setWindowTitle('Mandelbrot Set')
self.show()
# 在绘制曼德博集合图形的方法
self.draw_mandelbrot()
def draw_mandelbrot(self):
# 设置绘图参数
width, height = 800, 800
xmin, xmax = -2.0, 1.0
ymin, ymax = -1.5, 1.5
max_iter = 256
# 创建一个空白图像
mandelbrot_image = np.zeros((width, height))
# 生成曼德博集合图像
for x in range(width):
for y in range(height):
zx, zy = x * (xmax - xmin) / (width - 1) + xmin, y * (ymax - ymin) / (height - 1) + ymin
c = zx + zy * 1j
z = c
for i in range(max_iter):
if abs(z) > 2.0:
break
z = z * z + c
mandelbrot_image[x, y] = i
# 清空Figure并绘制曼德博集合图像
self.figure.clear()
ax = self.figure.add_subplot(111)
ax.imshow(mandelbrot_image.T, cmap='hot', extent=(xmin, xmax, ymin, ymax))
ax.set_title('Mandelbrot Set')
ax.set_xlabel('Real')
ax.set_ylabel('Imaginary')
# 更新图形画布
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
mandelbrotWin = MandelbrotWindow()
sys.exit(app.exec_())