How to return point color in Python scatterplot

Is there a way to get the color (or a simple yes / no answer if color is present) from the x, y coordinates of a matplotlib scatter plot?

Basically, I want to give a coordinate (x, y) and see if there is a colored circle at that position in my plot.

Any help would be appreciated.

+3


source to share


2 answers


To determine if there is a circle of scattering in position (xi,yi)

, there is no straight line. The problem is that (xi,yi)

are given in data coordinates and the circle is drawn as a circle in the displayed coordinates. This means that the circle in display coordinates can be an ellipse in data coordinates when the axis scaling is different for the x and y axis.

Matplotlib contains some functionality to determine if a point given in display coordinates is within the artist's degree. I want to use this, I need to draw the canvas first. It would then be possible to simulate the mouse event at the position (xi,yi)

and determine if it removes any artist from the scatter. Then the corresponding color can be obtained.



import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import matplotlib.backend_bases

x = np.random.rayleigh(size=10)
y = np.random.normal(size=10)
c = np.random.rand(10)

fig, ax = plt.subplots()
sc = ax.scatter(x,y,c=c, s=49, picker=True)

fig.canvas.draw()

def color_at_pos(xi,yi):
    xi, yi = ax.transData.transform((xi,yi))
    me = matplotlib.backend_bases.LocationEvent("no", fig.canvas, xi, yi)
    cont, ind = sc.contains(me)
    return sc.cmap(sc.norm(sc.get_array()[ind["ind"]]))

col = color_at_pos(1.25931,0.145889)
print col
col = color_at_pos(0.7,0.7)
print col

plt.show()

      

Here the first point (1.25931,0.145889)

works in two circles, so two colors are printed, and the second point is not in any circle and an empty array is printed.

+1


source


You can use get_color () for example.

a = plt.plot(x,c, color="blue", linewidth=2.0, linestyle="-")
b = plt.plot(x,s, color="red", linewidth=2.0, linestyle="-")

print a[0].get_color()
print b[0].get_color()

>>blue
>>red

      



Or you can assign the returned colors to variables to work with:

color_a = a[0].get_color()

if color_a == 'blue':
    ..do something

      

0


source







All Articles