Highlight matplotlib points that go over or under a threshold in colors based on the amount the boundaries are crossed

前端 未结 2 1117
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 13:46

I have a graph that looks like this:

\"\"

And the code I\'m running to get this graph (one of a sequence of

相关标签:
2条回答
  • 2021-01-03 13:58

    You can use boolean masks to select points that fulfill certain conditions, and plot them:

    import matplotlib.pyplot as plt
    import numpy as np
    
    std = 0.1
    N = 100
    
    x = np.linspace(0, 1, N)
    expected_y = np.sin(2 * np.pi * x)
    y = expected_y + np.random.normal(0, std, N)
    
    dist = np.abs(y - expected_y) / std
    
    mask1 = (1 < dist) & (dist <= 2)
    mask2 = dist > 2
    
    plt.fill_between(x, expected_y - 0.1, expected_y + 0.1, alpha=0.1)
    plt.fill_between(x, expected_y - 0.2, expected_y + 0.2, alpha=0.1)
    
    plt.plot(x, y)
    plt.plot(x[mask1], y[mask1], 'x')
    plt.plot(x[mask2], y[mask2], 'x')
    
    
    plt.tight_layout()
    plt.savefig('mp_points.png', dpi=300)
    

    Result:

    0 讨论(0)
  • 2021-01-03 14:13

    Use boolean indexing to identify these points and plot them separately:

    import numpy as np
    x = np.random.rand(20)
    
    b = x > 0.7
    
    print(b)
    print(x[b])
    
    0 讨论(0)
提交回复
热议问题