【问题标题】:How to change the color of an animated line in matplotlib?如何更改 matplotlib 中动画线的颜色?
【发布时间】:2021-12-22 07:56:44
【问题描述】:

我只是想知道如何根据频率更改动画正弦线的颜色。现在,它是我存储在名为 w 的变量中的频率。但是,我不知道如何进行颜色更改的更新。

到目前为止我的代码是:

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)

【问题讨论】:

    标签: python matplotlib animation simulation


    【解决方案1】:

    类似:

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

    【讨论】:

    • 谢谢!!!你救了我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2020-02-06
    相关资源
    最近更新 更多