How colored data points are based on some rules in matplotlib

I have a signal, and I would like to paint a red dot that are too far from the average 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 data 20 and 0 in red points, and I give them a special label, for example, “warning”. I am reading matplotlib: how to change the color of data points based on some variable , but I'm not sure how to apply it in my case

+4
source share
2 answers

, .
. , . , , numpy , True. ~.

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()

, :

enter image description here

+9

, :

import numpy as np
import matplotlib.pyplot as plt

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

# Calculate an outlier limit (I chose 2 Standard deviations from the mean)
k_bar = np.mean(k)
outlier_limit = 2*np.std(k)
# Generate a colour vector
kcolors = ['red' if abs(value - k_bar) > outlier_limit else 'yellow' for value in k]

#Plot using the colour vector
plt.scatter(x2,k, label="signal", c = kcolors)
plt.show()
+4

Source: https://habr.com/ru/post/1608020/


All Articles