【问题标题】:Different color for line depending on corresponding values in Pyplot根据 Pyplot 中的相应值,线条的不同颜色
【发布时间】:2016-06-13 10:41:02
【问题描述】:

我想根据相应的布尔数组的值(在本例中为 annotation)以不同的颜色显示折线图的各个部分。到目前为止,我已经尝试过:

plt.figure(4)
plt.title("Signal with annotated data")
plt.plot(resampledTime, modulusOfZeroNormalized, 'r-', )
walkIndex = annotation == True
plt.plot(resampledTime[~walkIndex], modulusOfZeroNormalized[~walkIndex], label='none', c='b')
plt.plot(resampledTime[walkIndex], modulusOfZeroNormalized[walkIndex], label='some', c='g')
plt.show()

但是这个加入了两种颜色,背景色也是可见的。

我遇到了BoundaryNorm,但我认为它需要 y 值。

任何想法如何在某些地区对线条进行不同的着色?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    以下是您的问题的有效解决方案:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    
    # construct some data
    n = 30
    x = np.arange(n+1)           # resampledTime
    y = np.random.randn(n+1)     # modulusOfZeroNormalized
    annotation = [True, False] * 15
    
    # set up colors 
    c = ['r' if a else 'g' for a in annotation]
    
    # convert time series to line segments
    lines = [((x0,y0), (x1,y1)) for x0, y0, x1, y1 in zip(x[:-1], y[:-1], x[1:], y[1:])]
    colored_lines = LineCollection(lines, colors=c, linewidths=(2,))
    
    # plot data
    fig, ax = plt.subplots(1)
    ax.add_collection(colored_lines)
    ax.autoscale_view()
    plt.show()
    

    顺便说一句,这条线

    walkIndex = annotation == True
    

    至少不是必需的,因为如果将布尔数组与True 进行比较,结果将是相同的。因此,您只需写:

    positive[annotation]
    

    【讨论】:

      【解决方案2】:

      我使用以下代码解决了它,但我认为这是一个相当“粗略”的解决方案

      plt.figure(4)
      plt.title("Signal with annotated data")
      
      walkIndex = annotation == True
      positive = modulusOfZeroNormalized.copy()
      negative = modulusOfZeroNormalized.copy()
      
      positive[walkIndex] = np.nan
      negative[~walkIndex] = np.nan
      plt.plot(resampledTime, positive, label='signal', c='r')
      plt.plot(resampledTime, negative, label='signal', c='g')
      

      与本文中的解决方案类似: Pyplot - change color of line if data is less than zero?

      【讨论】:

      • 你可以用np.ma.masked代替np.nan,然后matplotlib排除它
      猜你喜欢
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 2016-02-04
      • 2016-10-19
      • 1970-01-01
      相关资源
      最近更新 更多