2017-08-23 100 views
2

我有一個非常具體的問題。我有兩個numpy數組,每個數組的相應元素表示一個2d點。散點圖標記大小計算

a = [1,2,1,6,1] 

b = [5,0,3,1,5] 

我想繪製一個散點圖,其中標記的大小是基於點數發生的次數。

即:

1,5 : 2 

2,0 : 1 

1,3 : 1 

6,1 : 1 

所以尺寸數組必須是尺寸= [2,1,1,1]和其它兩個陣列可以是

a = [1,2,1,6]b = [5,0,3,1]

所以我必須能夠撥打plt.scatter如下:

plt.scatter(a,b,s=size) 

回答

2

由於問題被打上numpy的,我們可能會使用numpy的。 numpy.unique允許計算數組的唯一值的計數。

import numpy as np 

a = [1,2,1,6,1] 
b = [5,0,3,1,5] 

u, c = np.unique(np.c_[a,b], return_counts=True, axis=0) 

然後

# u= 
[[1 3] 
[1 5] 
[2 0] 
[6 1]] 
# c= 
[1 2 1 1] 

這可以被繪製像這樣,其中的附加功能可被用於標準化計數到某個點尺寸繪製

import matplotlib.pyplot as plt 
s = lambda x : (((x-x.min())/float(x.max()-x.min())+1)*8)**2 

plt.scatter(u[:,0],u[:,1],s=s(c)) 

plt.show() 

enter image description here

+0

這確實解決了我的問題。但有一點是,當我在python 2.7中試用它時,參數'axis'不起作用。爲什麼? –

+0

我自己使用python 2.7,所以這與python版本無關,但與您使用的numpy版本無關。 'axis'參數已被添加到numpy版本1.13.0中。 – ImportanceOfBeingErnest

1

Th是會做你想要什麼:

from collections import Counter 

a = [1, 2, 1, 6, 1] 
b = [5, 0, 3, 1, 5] 

counts = Counter([(x, y) for x, y in zip(a, b)]) 

size = [counts[(x, y)] for x, y in zip(a, b)] 

counter會跟蹤每個點有多少次出現在你的陣列。然後尺寸從counter獲得該數字。

請注意,您實際上需要size = [2, 1, 1, 1, 2],因爲您需要s與您的輸入陣列具有相同的尺寸。儘管這並不重要,你只需要將相同點重複兩次。

如果您確實想刪除重複項,您可以做同樣的事情,但是可以添加一個額外的步驟,您可以在其中創建set個點。

from collections import Counter 

a = [1, 2, 1, 6, 1] 
b = [5, 0, 3, 1, 5] 

counts = Counter([(x, y) for x, y in zip(a, b)]) 

points = set([(x, y) for x, y in zip(a, b)]) 
a = list() 
b = list() 
for x, y in points: 
    a.append(x) 
    b.append(y) 

size = [counts[(x, y)] for x, y in zip(a, b)]