2015-11-19 40 views
3

我正在使用pyplot從python中的數千個點開始繪製散點圖。我的問題是他們傾向於集中在一個地方,而這只是一大堆點。Pyplot Scatter Contour plot

是否有某種功能可以使pyplot繪圖點直到達到某個臨界密度,然後使其成爲等值線圖?

我的問題類似於this one,其中示例圖具有等高線,其中顏色表示繪製點的密度。

Super cool contour plot

感謝

編輯:這是我的數據看起來像Lots of yellow points

+1

您可能不必切換。如果點是鬆散的,那麼輪廓線不會太明顯,但點本身將傳達信息。但是,如果點像上圖那樣密集,那麼它們將創建一個很好的背景,「輪廓」應該可見。所以我建議首先使用帶有填充標記的'scatter'和頂部的'contour'。你只需要定義一個密度,你可以「輪廓」繪製。如果這不適合你,*然後*嘗試做一個開關,可能到'contourf'。 –

+0

爲什麼不只是減少你的點的大小?或使用一些透明度,這將有效地給你一個灰度的密度? – Julien

回答

5

首先,你需要你的數據的密度估計。根據您選擇的方法,可以獲得varying result

讓我們假設你想要做基礎上scipy.stats.gaussian_kde例子高斯密度估計,你可以得到密度高:

def density_estimation(m1, m2): 
    X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]              
    positions = np.vstack([X.ravel(), Y.ravel()])              
    values = np.vstack([m1, m2])                   
    kernel = stats.gaussian_kde(values)                 
    Z = np.reshape(kernel(positions).T, X.shape) 
    return X, Y, Z 

然後,您可以用contour

繪製它
X, Y, Z = density_estimation(m1, m2) 

fig, ax = plt.subplots()     

# Show density 
ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r,              
      extent=[xmin, xmax, ymin, ymax]) 

# Add contour lines 
plt.contour(X, Y, Z)                   

ax.plot(m1, m2, 'k.', markersize=2)  

ax.set_xlim([xmin, xmax])                   
ax.set_ylim([ymin, ymax])                   
plt.show() 

作爲替代方法,您可以根據密度更改標記顏色,如here所示。

+0

嘿,謝謝你的回答!它看起來像是陷入了'Z = np.reshape(kernel(positions).T,X.shape)'行。有沒有其他方法可以做同樣的事情? – Matthew

+0

這會引發錯誤消息:'NameError:全局名稱'xmin'未定義'。我*假設*它應該是'min(m1)'。 – Annan

+0

是的,它們沒有在_snippet_中定義。它們來自'gaussian_kde'函數的引用。 – memoselyk