2017-04-03 59 views
3

有沒有辦法從matplotlib散點圖的x,y座標中獲取顏色(如果存在顏色,那麼是簡單的yes/no answer)?如何返回scatterplot中點的顏色Python

基本上我想給出一個座標(x,y),並知道在我的情節中該位置是否有彩色圓圈。

任何幫助將不勝感激。

回答

0

您可以使用get_color()例如

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 

或者你可以將返回的顏色變量一起工作:

color_a = a[0].get_color() 

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

我懷疑這是什麼意思的問題。 – ImportanceOfBeingErnest

+0

好的,我會刪除它,事實證明是這樣。 – Jon

1

要確定是否有在一個位置(xi,yi)分散圈是不是直線前進。問題是(xi,yi)在數據座標中給出,而圓形在顯示座標中繪製爲圓形。這意味着當x軸和y軸的軸縮放比例不同時,顯示座標中的圓可能會在數據座標中成爲橢圓。

Matplotlib包含一些功能來確定在顯示座標中給定的點是否在藝術家範圍內。我爲了使用這個,畫布首先被繪製。然後,人們可以在位置(xi,yi)處模擬鼠標事件,並檢測它是否從分散點擊中任何藝術家。然後可以檢索相應的顏色。

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() 

這裏,第一點是(1.25931,0.145889)實際工作兩個圓內,所以兩種顏色打印,而第二點是不以任何圓並打印一個空數組。

+0

非常感謝。這是我需要的。 – Ilze