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


i trying figure out if there built pyplot change color of line depending on whether or not data negative or positive. example, if negative i'd line red , if it's positive i'd line different color, black.

is there in library lets me this? 1 thing i've thought of split data 2 sets of positive , negative , plotting them separately i'm wondering if there better way.

i make 2 datasets , setting right masks. using approach wont have lines between different positive parts.

import matplotlib.pyplot plt import numpy 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


Comments