目录
- 图像绘制代码
- 结果显示
- 参考
图像绘制代码
import time
import numpy as np
import matplotlib.pyplot as plt
class Guess:
def __init__(self, bbox=(-1.5, 1.5), resolution=50, lines=20, scale=1.2) -> None:
"""
bbox: 控制画格的大小
resolution: 控制爱心的分辨率
lines: 控制等高线的数量
scale: 心脏缩放的系数
"""
self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax = bbox * 3
plt.ion()# 开启画布动态模式
self.scale = scale
# scale: 心脏缩放的系数 设置为全局变量
self.time = time.time()
A = np.linspace(self.xmin, self.xmax, resolution)
self.B = np.linspace(self.xmin, self.xmax, lines)
self.A1, self.A2 = np.meshgrid(A, A)
def coordinate(self, x, y, z):
return (x ** 2 + (9 / 4) * y ** 2 + z ** 2 - 1) ** 3 - x ** 2 * z ** 3 - (9 / 80) * y ** 2 * z ** 3
def draw(self, ax, coef):
# coef: 使得心脏可以按照时间跳动
for z in self.B:
X, Y = self.A1, self.A2
Z = self.coordinate(X, Y, z) + z
cset = ax.contour(X * coef, Y * coef, Z * coef, [z * coef], zdir='z', colors=('pink',))
for y in self.B:
X, Z = self.A1, self.A2
Y = self.coordinate(X, y, Z) + y
cset = ax.contour(X * coef, Y * coef, Z * coef, [y * coef], zdir='y', colors=('pink',))
for x in self.B:
Y, Z = self.A1, self.A2
X = self.coordinate(x, Y, Z) + x
cset = ax.contour(X * coef, Y * coef, Z * coef, [x * coef], zdir='x', colors=('pink',))
def run(self, count):
#加入count是我们想循环的次数
fig = plt.figure()
for i in range(count):
plt.clf()# 每次清除画布
ax = fig.add_subplot(projection='3d')
ax.set_title("2luyao")
ax.set_zlim3d(self.zmin, self.zmax)
ax.set_xlim3d(self.xmin, self.xmax)
ax.set_ylim3d(self.ymin, self.ymax)
times = time.time() - self.time # 计算画布的当前时间状态
ax.view_init(10, 100 + np.cos(times) * 10)# 让三维坐标图可以变换坐标展示
# coef 是用来放缩心脏的大小的,加入cos来使它有节奏的跳动
coef = np.cos(times) * (self.scale - 1) + 1
self.draw(ax, coef)
plt.pause(0.1) # 让绘制出来的心脏可以显示
plt.show()
if __name__ == '__main__':
demo = Guess()
demo.run(50)
结果显示
这是一个动态的爱心,可以试验一下
参考
https://blog.csdn.net/qq_44961028/article/details/127778513