In a plot, how can I color all values above a threshold in a different color? Like everything above mean + std or mean + 2*std ?
Using a LineCollection is the proper way to go, but you can also do an easy version in one line of code using masked arrays:
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
# make a weird continuous function
r, t = np.random.random((100,)), np.arange(0, 100, .01)
y = sum(r[3*i+0]*np.sin(r[3*i+1]*t + 10*r[3*+2]) for i in range(10))
# generate the masked array
mask = ma.masked_less(y, 1.1)
plt.plot(t, y, 'k', linewidth=3)
plt.plot(t, mask, 'r', linewidth=3.2)
plt.show()
The cheat here is that it draws over the original data with the filtered data so sometimes the underlying curve can show, depending on how it's rendered. I made the red line here a bit thicker, but I'm not sure whether it made a difference. The advantage is that it's basically one line, ma.masked_less(y, 1.1)
, for a threshold of 1.1
.
The reason masked arrays are needed here is that otherwise there would be a line connecting the different segments, and the mask causes these points to not be plotted.