写一个 Python 在 Jupyter Notebook 上绘制能动的爱心形状的 3D 图的代码
时间: 2024-09-27 08:15:38 浏览: 178
要在Jupyter Notebook上使用Python绘制动态的3D爱心形状,我们可以使用matplotlib库的animation模块结合mayavi库,因为mayavi对于3D图形处理更为强大。这里是一个简单的例子,我们将创建一个爱心三维旋转动画:
首先,确保已经安装了所需的库:
```bash
pip install numpy matplotlib mayavi
```
然后,在Jupyter Notebook中编写代码:
```python
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mayavi import mlab
# 创建爱心函数
def create_heart_shape(x, y):
return (x**2 + y**2 - 1)**0.5 * ((x**2 + y**2) / 2)**0.75
# 初始化数据
n_points = 100
r = np.linspace(-1, 1, n_points)
theta = np.linspace(0, 2*np.pi, n_points).reshape(-1, 1)
x, y = r * np.cos(theta), r * np.sin(theta)
# 创建3D图并初始化线条
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
line, = ax.plot([], [], [], 'o', animated=True)
# 定义更新函数
def update(frame):
line.set_data(x[frame], y[frame])
line.set_3d_properties(create_heart_shape(x[frame], y[frame]))
return line,
# 创建动画
anim = FuncAnimation(fig, update, frames=np.arange(len(x)), interval=50, blit=True)
# 显示动画
plt.show()
阅读全文
相关推荐


















