Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Is it possible to change line color in a plot if exceeds a specific range?

Is it possible to change the line color in a plot when values exceeds a certain y value? Example:

import numpy as np
import matplotlib.pyplot as plt
a = np.array([1,2,17,20,16,3,5,4])
plt.plt(a)

This one gives the following: enter image description here

I want to visualise the values that exceeds y=15. Something like the following figure:

enter image description here

Or something like this(with cycle linestyle):enter image description here:

Is it possible?

like image 931
Mpizos Dimitris Avatar asked May 08 '15 10:05

Mpizos Dimitris


People also ask

How do you change the range of a plot in Python?

MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.


2 Answers

Basically @RaJa provides the solution, but I think that you can do the same without loading an additional package (pandas), by using masked arrays in numpy:

import numpy as np
import matplotlib.pyplot as plt

a = np.array([1,2,17,20,16,3,5,4])

# use a masked array to suppress the values that are too low
a_masked = np.ma.masked_less_equal(a, 15)

# plot the full line
plt.plot(a, 'k')

# plot only the large values
plt.plot(a_masked, 'r', linewidth=2)

# add the threshold value (optional)
plt.axhline(15, color='k', linestyle='--')
plt.show()

Result: enter image description here

like image 180
hitzg Avatar answered Sep 19 '22 20:09

hitzg


I don't know wether there is a built-in function in matplolib. But you could convert your numpy array into a pandas series and then use the plot function in combination with boolean selection/masking.

import numpy as np
import pandas as pd

a = np.array([1,2,17,20,16,3,5,4])
aPandas = pd.Series(a)
aPandas.plot()
aPandas[aPandas > 15].plot(color = 'red')
like image 45
RaJa Avatar answered Sep 20 '22 20:09

RaJa