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()
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.
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" .
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 .
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 .
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With