Home > Net >  How do I animate several lines at once on a polar plot with matplotlib?
How do I animate several lines at once on a polar plot with matplotlib?

Time:06-30

I have 35 different radial lines that I am displaying on a polar plot that I would like to animate as their angular dispersion increases. If I just want to animate one line I would do something like this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

speed = 5.5
weight=0.5
angle=0

fig = plt.figure(figsize=(12, 12))
ax = plt.subplot(111, projection = 'polar')
ax.set_theta_direction(-1)
ax.set_theta_offset(np.pi / 2.0)
line, = ax.plot([0, angle], [0, speed],color='blue',linewidth=3,alpha=weight) 
def animate(i):
    angle=i*(np.pi/180)
    new_datax = [0, angle]
    lines.set_xdata(new_datax)
    return lines,
anim = animation.FuncAnimation(fig, animate, frames=360, interval=20)

And that seems to spin round quite nicely! However if "speed, weight and angles" are arrays not just values how can I animate them all at once without having to do 35 different set_xdata? I know it's not like this!

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

speeds = np.array([5.5,5.5,5.1,5.5,5.6,5.7,5.8,6,6.5,7,7.5,8.5,9.5,11.5,17.5,23,26,29,32,27,22,14.5,9.5,6.3,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10,10])
weights = np.array([1,0.93,0.90,0.86,0.83,0.83,0.83,0.83,0.82,0.80,0.73,0.77,0.72,0.68,0.68,0.70,0.59,0.71,0.71,0.64,0.73,0.77,0.74,0.680.636977,0.59,0.54,0.53,0.51,0.48,0.46,0.40,0.44,0.38,0.36])
angles=np.linspace(0,0,35)*(np.pi/180)

fig = plt.figure(figsize=(12, 12))
ax = plt.subplot(111, projection = 'polar')
ax.set_theta_direction(-1)
ax.set_theta_offset(np.pi / 2.0)
for j in range (35):
    lines, = ax.plot([0, angles[j]], [0, speeds[j]],color='blue',linewidth=3,alpha=weight3[j]) 

def animate(i):
    angles=np.linspace(0,i,35)*(np.pi/180)
    for j in range(35):
        new_datax = [0, angles[j]]
        lines.set_xdata(new_datax)
    return lines,
anim = animation.FuncAnimation(fig, animate, frames=360, interval=20)

But I don't know how else to approach this problem! Any help would be greatly appreciated!

CodePudding user response:

You need to keep track of all the line objects. Right now you're overwriting the lines object every time. Something like this should work:

lines = []
for j in range(35):
    line, = ax.plot([0, angles[j]], [0, speeds[j]], color='blue', linewidth=3, alpha=weights[j])
    lines.append(line)


def animate(i):
    angles = np.linspace(0, i, 35) * (np.pi / 180)
    for j in range(35):
        new_datax = [0, angles[j]]
        lines[j].set_xdata(new_datax)
    return lines,


anim = animation.FuncAnimation(fig, animate, frames=360, interval=20)
  • Related