代码之家  ›  专栏  ›  技术社区  ›  Mazin

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

  •  3
  • Mazin  · 技术社区  · 8 年前

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

    Example results

    2 回复  |  直到 8 年前
        1
  •  3
  •   Bart    8 年前

    在用特定颜色打印新线之前,可以在旧线上循环并设置线颜色。不幸地 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')
    

    enter image description here

        2
  •  1
  •   tmdavison    8 年前

    你可以使用 line.set_color('k') 绘制线后设置线的颜色,其中 line 是matplotlib Line2D 例子幸运的是,我们可以从 Axes 列表中的实例 ax.lines ,所以这只是在绘制新行之前循环该列表并将所有行设置为黑色的一种情况。我们可以用一行简单的代码做到这一点:

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

    enter image description here enter image description here enter image description here