Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple colors in the one graph in Matplotlib

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: enter image description here

Now is it possible to display the data above this line ( 100 in this case) in some other color ?

like image 975
KarateKid Avatar asked Aug 15 '26 17:08

KarateKid


1 Answers

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:

enter image description here

like image 120
HYRY Avatar answered Aug 17 '26 07:08

HYRY