我现在有以下代码,以显示曲线的增长:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
def move_curve(i, line, x, y, z):
# Add points rather than changing start and end points.
line.set_data(x[:i+1], y[:i+1])
line.set_3d_properties(z[:i+1])
fig = plt.figure()
ax = fig.gca(projection='3d')
x = [1, 3, 8, 11, 17]
y = [7, 2, -5, 3, 5]
z = [5, 7, 9, 13, 18]
i = 0
line = ax.plot([x[i], x[i+1]], [y[i],y[i+1]], [z[i],z[i+1]])[0]
ax.set_xlim3d([1, 17])
ax.set_ylim3d([-5, 7])
ax.set_zlim3d([5, 18])
line_ani = animation.FuncAnimation(fig, move_curve, 5, fargs=(line, x, y, z))
plt.show()
我想以不同的颜色显示不同的线条。此外,我想在曲线增长时更新轴的长度。
怎么做?我是python的新手,所以我可能会遗漏一些简单的东西。谢谢你的帮助!
答案 0 :(得分:2)
以下是@ MrT的答案看起来像使用FuncAnimation。优点是您不需要关心自动缩放;这是在飞行中自动完成的。
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import mpl_toolkits.mplot3d.axes3d as p3
fig = plt.figure()
ax = fig.gca(projection='3d')
x = [1, 3, 8, 11, 17]
y = [7, 2, -5, 3, 5]
z = [5, 7, 9, 13, 18]
#colour map
colors = ["green", "blue", "red", "orange"]
def init():
ax.clear()
def update(i):
newsegm, = ax.plot([x[i], x[i + 1]], [y[i], y[i + 1]], [z[i], z[i + 1]], colors[i])
ani = anim.FuncAnimation(fig, update, init_func=init,
frames = range(len(x)-1), interval = 300, repeat=True)
plt.show()
答案 1 :(得分:1)
您可以使用ArtistAnimation
并将单个颜色归因于每个线段:
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import mpl_toolkits.mplot3d.axes3d as p3
fig = plt.figure()
ax = fig.gca(projection='3d')
x = [1, 3, 8, 11, 17]
y = [7, 2, -5, 3, 5]
z = [5, 7, 9, 13, 18]
#colour map
cmap = ["green", "blue", "red", "orange"]
#set up list of images for animation with empty list
lines=[[]]
for i in range(len(x) - 1):
#create next segment with new color
newsegm, = ax.plot([x[i], x[i + 1]], [y[i], y[i + 1]], [z[i], z[i + 1]], cmap[i])
#append new segment to previous list
lines.append(lines[-1] + [newsegm])
#animate list of line segments
ani = anim.ArtistAnimation(fig, lines, interval = 300)
plt.show()
输出: