在Python MatPlotLib中使用动画时,如何更改绘制曲线的颜色? [英] How to change color of plotted curves when using Animations in Python MatPlotLib?
问题描述
我有一段代码使用Python MatPlotLib中的FuncAnimation方法来生成50条随机的指数衰减曲线,并在生成曲线时更新显示彼此的曲线,每条曲线都以不同的颜色显示.我希望能够将previos曲线变灰,因为新的曲线是用固定的颜色生成的,例如Blue.我希望有人能提供帮助.
I have a piece of code that uses the FuncAnimation method in Python MatPlotLib to generate 50 random Exponential Decay Curves and updating the plot showing each one other the curves as they re generated.Each curves shows up with different colors. I would like to be able to gray out the previos curves as the new one is generated in a set color, say Blue. I hope someone can help.
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)
:
you have to store the line instance which plot
returns and call set_color(color)
before you draw again:
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()
这篇关于在Python MatPlotLib中使用动画时,如何更改绘制曲线的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!