Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to color data points based on some rules in matplotlib

I have a signal, and I would like to color in red point which are too far from the mean of the signal. For example:

k=[12,11,12,12,20,10,12,0,12,10,11]
x2=np.arange(1,12,1)
plt.scatter(x2,k, label="signal")
plt.show()

I would like to color in red the data points 20 and 0, and I give them a special label like "warning". I read matplotlib: how to change data points color based on some variable, but I am not sure how to apply it on my case

like image 248
user3841581 Avatar asked Sep 18 '15 13:09

user3841581


1 Answers

If you want different labels, you need different plots.
Filter your data according to your formula.
In this case I took values which are more than 1.5 standard deviations away from the mean. In case you don't know, in numpy you can use boolean masks to index arrays and only take elemets where the mask is True. You can also easily flip the mask with the complement operator ~.

import matplotlib.pyplot as plt
import numpy as np

k=np.array([12,11,12,12,20,10,12,0,12,10,11])
x2=np.arange(1,12,1)

# find out which parameters are more than 1.5*std away from mean
warning = np.abs(k-np.mean(k)) > 1.5*np.std(k)

# enable drawing of multiple graphs on one plot
plt.hold(True)

# draw some lines behind the scatter plots (using zorder)
plt.plot(x2, k, c='black', zorder=-1)

# scatter valid (not warning) points in blue (c='b')
plt.scatter(x2[~warning], k[~warning], label='signal', c='b')

# scatter warning points in red (c='r')
plt.scatter(x2[warning], k[warning], label='warning', c='r')

# draw the legend
plt.legend()

# show the figure
plt.show()

This is what you get:

enter image description here

like image 173
swenzel Avatar answered Nov 16 '22 02:11

swenzel