Ank
Ank

Reputation: 1904

Matplotlib animation: draw lines in different colours

I have the following code right now, to show growth of a curve:

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()

I want to show the different lines in different colours. Also, I want to update the length of the axis as the curve grows.

How to do that? I am new to python so I might be missing something simple. Thanks for the help!

Upvotes: 0

Views: 1502

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339230

Here is how @MrT's answer would look like using FuncAnimation. The advantage is that you do not need to care about autoscaling; that is done automatically on the fly.

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()

enter image description here

Upvotes: 2

Mr. T
Mr. T

Reputation: 12410

You can use ArtistAnimation and attribute an individual colour to each line segment:

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()

Output:

enter image description here

Upvotes: 1

Related Questions