问题
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.
回答1:
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()
回答2:
The scatter plot is a PathCollection
as mentioned by the other answer. It has a get_facecolors()
method which returns the color used to render each point. However, the correct colors are only returned once the scatter plot is rendered. So, we can first trigger a plt.draw()
and then use get_facecolors()
.
Working example:
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 = ax.scatter(x, y, c=c, cmap='viridis')
idx = 2
plt.draw()
col = sc.get_facecolors()[idx].tolist()
ax.annotate("hello", xy=(x[idx],y[idx]), color=col,
xytext=(5,5), textcoords="offset points")
plt.show()
which generates
来源:https://stackoverflow.com/questions/47908429/get-color-of-a-scatter-point