2012-08-08 54 views
1

如果我在matplotlib的散點圖返回一個CircleCollection:重置一個已經繪製的散點在matplotlib

coll = plt.scatter(rand(5), rand(5), c="k")

我怎麼能重置只是特定點的顏色?我注意到coll不可迭代。我只想修改已繪製點的面/邊顏色,儘管它們已經從最初的plt.scatter調用中設置了顏色。如何才能做到這一點?

例如:只是改變了第二點的顏色繪製的,例如:

coll[1].set_color("r") # this does not work, coll not indexable this way

我知道可以在scatter傳遞的顏色矢量,以c=但我想故意重置因爲當最初調用plt.scatter時,所有點的顏色都不知道。 :

編輯:進一步說明。我正在尋找最簡單的方法來根據不同的條件對散點中的點進行着色。如果points是一個二維數組,並且您用scatter(points[:, 0], points[:, 1], c-"k")來繪製它,則稍後基於某些條件(例如,

# replot certain points in red with alpha 
selected = points[:, 0] > 0.5 
plt.scatter(selected[:, 0], selected[:, 1], c="r", alpha=0.5) 

這裏我重新繪製了舊點,但是這是凌亂的,因爲新的點與阿爾法繪製,因此它不會給預期的效果。根據哪些點必須重新着色的各種條件可能比較複雜,並且比最初分散時發生的時間更晚發生,所以僅僅能夠改變現有點的顏色是方便的,而不是基於並根據情況分別繪製它們。

回答

1

這適用於我。可能您需要在fig.show之前撥打plt.draw(或不是)。

coll = plt.scatter(rand(5), rand(5), c="k") 
fig = plt.gcf() 
fig.show() # or fig.savefig("a.png") 

coll.set_color(['b', 'g', 'r', 'y', 'k']) 
fig.show() # or fig.savefig("b.png") 

更新

這是如何修改部分的顏色。如果在調用scatter時使用單色,則需要明確地擴展colors數組。

num = 5 
coll = plt.scatter(rand(num), rand(num), c='k') 
# coll = plt.scatter(rand(num), rand(num), c=['b', 'g', 'r', 'y', 'k']) 
fig = plt.gcf() 
fig.show() 

colors = coll.get_facecolor() 
if colors.shape[0] == 1: 
    newcolors = np.tile(colors, (num, 1)) 
else: 
    newcolors = colors 
newcolors[0] = [0, 0.75, 0.75, 1] 
coll.set_color(newcolors) 
+0

爲什麼不首先獲取點的顏色矢量然後設置它,如:colors = coll.get_facecolors()[0]'然後修改'colors'並將它傳遞給'set_color'? – user248237dfsf 2012-08-08 17:50:11

+0

我更新了答案。閱讀'plt.scatter'文件,看看'set_color'的參數是如何根據其形狀來處理的。 – tkf 2012-08-08 21:20:15

1

您需要使用單獨的列表:

plt.scatter(x1, y1, c='b') 
plt.scatter(x2, y2, c='k') 

this

你也可以有一個與x和y長度相同的c列表。

+0

有沒有辦法做到這一點沒有單獨的列表?在繪製所有點將被着色時,我不一定知道 – user248237dfsf 2012-08-08 14:54:36

+0

您可以使用c列表而不是字母並在重做圖形之前逐個更改這些列表。 – 2012-08-08 15:03:36

+0

沒錯,但這意味着我必須在初始調用散射之前做所有顏色的計算,不是嗎? – user248237dfsf 2012-08-08 15:04:54

1

當你調用scatter,通過每個點的顏色,那麼你可以改變_facecolors ndarray直接。

from matplotlib import pyplot as plt 
from matplotlib.collections import PathCollection 
from numpy.random import rand 
x = rand(5) 
y = rand(5) 
coll = plt.scatter(x, y, c=["k"]*len(x)) # must set color for every point 
coll._facecolors[2,:] = (1, 0, 0, 1) 
plt.show()