gpt4 book ai didi

python - 在 Python MatPlotLib 中使用动画时如何更改绘制曲线的颜色?

转载 作者:太空狗 更新时间:2023-10-30 02:45:19 25 4
gpt4 key购买 nike

我有一段代码使用 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()

最佳答案

您必须存储 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()

plot result

关于python - 在 Python MatPlotLib 中使用动画时如何更改绘制曲线的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25111040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com