Pyplot - change color of line if data is less than zero?

前端 未结 3 441
耶瑟儿~
耶瑟儿~ 2020-12-28 22:24

I am trying to figure out if there is anything built into pyplot that will change the color of my line depending on whether or not the data is negative or positive. For exam

相关标签:
3条回答
  • 2020-12-28 23:04

    If you use a scatter plot you can give each point a different color:

    x = range(1)
    x = range(10)
    y = [i - 5 for i in x]
    c = [i < 0 for i in y]
    plt.scatter(x, y, c=c, s=80)
    

    enter image description here

    0 讨论(0)
  • 2020-12-28 23:06

    You can conditionally plot data in your axes object, using a where like syntax (if you're used to something like Pandas).

    ax.plot(x[f(x)>=0], f(x)[f(x)>=0], 'g')
    ax.plot(x[f(x)<0],  f(x)[f(x)<0],  'r')
    

    Technically, it's splitting and plotting your data in two sets, but it's fairly compact and nice.

    0 讨论(0)
  • 2020-12-28 23:24

    I would just make two datasets and setting the right masks. By using that approach i wont have lines between different positive parts.

    import matplotlib.pyplot as plt
    import numpy as np
    
    signal = 1.2*np.sin(np.linspace(0, 30, 2000))
    pos_signal = signal.copy()
    neg_signal = signal.copy()
    
    pos_signal[pos_signal <= 0] = np.nan
    neg_signal[neg_signal > 0] = np.nan
    
    #plotting
    plt.style.use('fivethirtyeight')
    plt.plot(pos_signal, color='r')
    plt.plot(neg_signal, color='b')
    plt.savefig('pos_neg.png', dpi=200)
    plt.show()
    

    Example

    0 讨论(0)
提交回复
热议问题