Is there a way to change the color of the graph about a certain threshold in python Matplotlib ?
plt.plot(temp)
plt.plot((0, len(temp)), (100, 100), 'b-')
plt.ylabel('Some data')
plt.show()
where temp contains some data
The final image looks soomething like this:

Now is it possible to display the data above this line ( 100 in this case) in some other color ?
You can use masked array to draw multiple lines. Here is an example:
Find the intersection points between curve and the threshold line, and insert the points to the original data. Then you can call plot() twice with masked array:
import numpy as np
import pylab as pl
def threshold_plot(x, y, th, fmt_lo, fmt_hi):
idx = np.where(np.diff(y > th))[0]
x_insert = x[idx] + (th - y[idx]) / (y[idx+1] - y[idx]) * (x[idx+1] - x[idx])
y_insert = np.full_like(x_insert, th)
xn, yn = np.insert(x, idx+1, x_insert), np.insert(y, idx+1, y_insert)
mask = yn < th
pl.plot(np.ma.masked_where(mask, xn), np.ma.masked_where(mask, yn), fmt_hi, lw=2)
mask = yn > th
pl.plot(np.ma.masked_where(mask, xn), np.ma.masked_where(mask, yn), fmt_lo)
pl.axhline(th, color="black", linestyle="--")
x = np.linspace(0, 3 * np.pi, 50)
y = np.random.rand(len(x))
threshold_plot(x, y, 0.7, "b", "r")
the result:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With