我想从y = (x - 3) * (x - 5) * (x - 7) + 85
到x=1
绘制曲线x=10
。我尝试使用animation.FuncAnimation()
在屏幕上设置动画该曲线,但无法正确执行。我在这里粘贴我的代码。如何为该曲线设置动画?
代码:
import matplotlib as mpl
mpl.rc('text', usetex = True) #for LaTex notation in
the Plot
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
title = 'Growing Curve.'
# First set up the figure, the axis, and the plot
element we want to animate
fig = plt.figure()
ax = plt.axes()
line, = ax.plot([], [], lw=2)
#plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])
def f(x):
y = (x - 3) * (x - 5) * (x - 7) + 85
return(y)
a, b = 2, 9
x = []
y = []
# initialization function: plot the background of
each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = np.arange(1, i, 0.001)
y = f(x)
line.set_data(x,y)
return line,
plt.xlabel('$x$')
ax.xaxis.set_label_coords(1.05, -0.025) #for putting
xlabel at the end of the axis
plt.ylabel('$y$')
ax.yaxis.set_label_coords(-0.025, 1.05)
plt.title(title, y = 1.03)
plt.ylim(ymin=0)
#plt.legend(loc='upper center', bbox_to_anchor=(0.5,
-0.19))
#Customize the axes and gridlines:
ax.grid(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
#TickMarks Customization:
ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([])
# Only show ticks on the left and bottom spines:
ax.xaxis.set_ticks_position('bottom')
anim = animation.FuncAnimation(fig, animate
,init_func=init,
interval=200,
blit=True, repeat=False)
anim.save('Curve.mp4', writer = 'ffmpeg', fps = 2,
dpi=50,extra_args=['-vcodec', 'libx264'])
plt.show()