python 交互式绘图最新线为彩色,其余为黑色

python interactive plot newest line in color, rest in black

我正在尝试使用 matplotlib 使用 plt.waitforbuttonpress(-1) 在 Python 中绘制多条线,以便我可以分别分析每条新线。但是在这样做时,我希望最新的行有颜色,其余的是黑色。我知道如何给新行添加颜色,但我似乎找不到将所有先前行重置为黑色的方法。这可能吗?例如:

您可以遍历旧线条并设置线条颜色,然后再使用某种颜色绘制新线条。不幸的是,plt.waitforbuttonpress() 似乎无法在我的电脑上运行,但类似这样的东西:

import numpy as np
import matplotlib.pylab as pl

pl.figure()
ax=pl.subplot(111)
for i in range(10):
    # 1. set all lines to a black color
    for l in ax.get_lines():
        l.set_color('k')

    # 2. plot the latest one in a red color
    pl.plot(np.arange(10), np.random.random(10), color='r')

您可以在绘制后使用line.set_color('k')设置线条的颜色,其中line是一个matplotlib Line2D实例。幸运的是,我们可以访问列表 ax.linesAxes 实例中的所有行,因此这只是循环遍历该列表并将所有行设置为黑色的情况,然后再绘制新行。我们可以用一行简单的代码来做到这一点:

[l.set_color('k') for l in ax.lines]

这是一个最小的例子:

import matplotlib.pyplot as plt
import numpy as np

plt.ion()

x = np.arange(5)
y = np.arange(5)

fig,ax = plt.subplots(1)

ax.set_xlim(0,4)
ax.set_ylim(0,6)

ax.plot(x,y,'r-')

plt.waitforbuttonpress(-1)

[l.set_color('k') for l in ax.lines]
ax.plot(x,y+1,'r-')

plt.waitforbuttonpress(-1)

[l.set_color('k') for l in ax.lines]
ax.plot(x,y+2,'r-')

plt.waitforbuttonpress(-1)