如何在Python Matplotlib的动画中改变绘制曲线的颜色?

5 投票
1 回答
13181 浏览
提问于 2025-04-18 15:52

我有一段代码,它使用Python的MatPlotLib库中的FuncAnimation方法来生成50条随机的指数衰减曲线,并且在每次生成新曲线时更新图表,显示所有的曲线。每条曲线的颜色都不一样。我希望在生成新曲线时,能够把之前的曲线变成灰色,比如说用蓝色来表示。希望有人能帮我解决这个问题。

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

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)       
def main(i):
    # Actual parameters
    A0 = 10 
    K0 = random.uniform(-15,-1)
    C0 = random.uniform(0,10)      

    # Generate some data based on these
    tmin, tmax = 0, 0.5
    num = 20
    t = np.linspace(tmin, tmax, num)
    y = model_func(t, A0, K0, C0)
    ax1.plot(t,y)
def model_func(t, A, K, C):   
        return A * np.exp(K * t)

ani = animation.FuncAnimation(fig, main, interval=1000)

plt.show()

1 个回答

6

你需要保存一下 plot 返回的线条实例,然后在重新绘制之前调用 set_color(color) 来设置颜色:

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

# an empty variable, whre we store the returned line of plot:
line = None

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)       
def main(i):

    # we have to make line global:
    global line

    # Actual parameters
    A0 = 10 
    K0 = random.uniform(-15,-1)
    C0 = random.uniform(0,10)      

    # Generate some data based on these
    tmin, tmax = 0, 0.5
    num = 20
    t = np.linspace(tmin, tmax, num)
    y = model_func(t, A0, K0, C0)
    # check if line already exists, if yes make it gray:
    if line is not None:
        line.set_color('gray')
    # plot returns a list with line instances, one for each line you draw,
    # the comma is used to unpack the one element list
    line, = ax1.plot(t,y, color='red') 

def model_func(t, A, K, C):   
        return A * np.exp(K * t)

ani = animation.FuncAnimation(fig, main, interval=1000)

plt.show()

绘图结果

撰写回答