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

I am trying to find out if there is anything built into pyplot that will change the color of my line depending on whether the data is negative or positive. For example, if this is negative, I would like the line to be red, and if it is positive, I would like the line to be a different color, for example, black.

Is there anything in the library that allows me to do this? One thing that I was thinking about is to split the data into two sets of positive and negative values ​​and decompose them separately, but I wonder if there is a better way.

+6
source share
3 answers

I would just make two datasets and set the correct masks. Using this approach, I will not 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

+10
source

You can conditionally display data in an axes object using the 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 building your data in two sets, but it's pretty compact and nice.

+4
source

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

+1
source

All Articles