问题描述
我有一个包含一些玩具数据的散点图.
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.
玩具示例:
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()
我需要以某种方式获取该点的颜色,并将我的 color ='green'
部分更改为 color = color_of_the_point
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?
颜色矢量 c
被转换为颜色图,并且还可以进行其他修改,例如归一化或alpha值.
The color vector c
is transformed to a colormap, and it can also have further modifications such as normalization or alpha value.
sc有一种检索点坐标的方法:
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.
推荐答案
散点图是另一个答案中提到的 PathCollection
.它有一个 get_facecolors()
方法,该方法返回用于渲染每个点的颜色.但是,仅在绘制散点图后才返回正确的颜色.所以,我们可以先触发一个plt.draw()
,然后使用get_facecolors()
.
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()
.
工作示例:
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()
生成
这篇关于获取散点的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!