Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get color of a scatter point

I have a scatter plot with some toy data.

I want to draw a label next to a given point with the color of the point.

Toy example:

x = 100*np.random.rand(5,1)
y = 100*np.random.rand(5,1)
c = np.random.rand(5,1)

fig, ax = plt.subplots()
sc = plt.scatter(x, y, c=c, cmap='viridis')

# I want to annotate the third point (idx=2)
idx = 2  
ax.annotate("hello", xy=(x[idx],y[idx]), color='green', 
            xytext=(5,5), textcoords="offset points")
plt.show()

enter image description here

I need to somehow get the color of this point and change my color='green' part for color=color_of_the_point

How can I get the color of a point in a scatter plot?

The color vector c is transformed to a colormap, and it can also have further modifications such as normalization or alpha value.

sc has a method for retrieving the coordinates of the points:

sc.get_offsets()

So it would be logical to also have a method for getting the color of the points but I could not find such method.

like image 454
Sembei Norimaki Avatar asked Dec 20 '17 14:12

Sembei Norimaki


People also ask

How do I color a data point in R?

To change the color and the size of points, use the following arguments: col : color (hexadecimal color code or color name). For example, col = "blue" or col = "#4F6228" .

How do you color code a scatter plot in R?

The different color systems available in R have been described in detail here. To change scatter plot color according to the group, you have to specify the name of the data column containing the groups using the argument groupName . Use the argument groupColors , to specify colors by hexadecimal code or by name .

Is it possible to create a Coloured scatterplot using matplotlib?

Use matplotlib. pyplot. scatter() to make a colored scatter plot. Using lists of corresponding x and y coordinates and a list colors , create a list color_indices that assigns each coordinate the index of a color from colors .


1 Answers

The scatter plot is a PathCollection, which subclasses ScalarMappable. A ScalarMappable has a method to_rgba. This can be used to get the color corresponding to the colorvalues.

In this case

sc.to_rgba(c[idx])

Note that the arrays used in the question are 2D arrays, which is normally undesired. So a complete example would look like

import matplotlib.pyplot as plt
import numpy as np

x = 100*np.random.rand(5)
y = 100*np.random.rand(5)
c = np.random.rand(5)

fig, ax = plt.subplots()
sc = plt.scatter(x, y, c=c, cmap='viridis')

# I want to annotate the third point (idx=2)
idx = 2  
ax.annotate("hello", xy=(x[idx],y[idx]), color=sc.to_rgba(c[idx]), 
            xytext=(5,5), textcoords="offset points")
plt.show()

enter image description here

like image 62
ImportanceOfBeingErnest Avatar answered Sep 22 '22 17:09

ImportanceOfBeingErnest