Home > Net >  How to change the color of an animated line in matplotlib?
How to change the color of an animated line in matplotlib?

Time:11-10

I just wanted to know how to change the color of my animated sine line depending on the frequency. Right now, it is a frequency that I store in a variable named w. However, I do not know how to make the update for the color change.

The code I have until now is:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(-6,6),ylim=(-1.5,1.5))
line,=ax.plot([],[])


def init():
    line.set_data([],[])
    return line,

w=list(range(0,5)) list(range(5,0,-1))


def animate(i):
    x=np.linspace(-6,6,1000)
    y = np.sin((x*w[i]))
    line.set_data(x,y)
    return line, 
    
anim = animation.FuncAnimation(fig, animate, init_func=init,
                                frames=10,interval=600,repeat=True)

CodePudding user response:

Something like:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import matplotlib as mpl
fig = plt.figure()
ax = plt.axes(xlim=(-6,6),ylim=(-1.5,1.5))
line,=ax.plot([],[])


def init():
    line.set_data([],[])
    return line,

w=list(range(0,5)) list(range(5,0,-1))

cmap = plt.cm.viridis
norm = mpl.colors.Normalize(vmin=0, vmax=5)

def animate(i):
    x=np.linspace(-6,6,1000)
    y = np.sin((x*w[i]))
    line.set_data(x,y)
    col = cmap(norm(w[i]))
    line.set_color(col)
    return line, 
    
anim = animation.FuncAnimation(fig, animate, init_func=init,
                                frames=10,interval=600,repeat=True)
plt.show()
  • Related