2017-05-19 104 views
1

所以我有代碼繪製了我的數據集的二維圖。我繪製它像這樣:刪除數據在散點圖(Python)中的一條線下

histogram = plt.hist2d(fehsc, ofesc, bins=nbins, range=[[-1,.5],[0.225,0.4]]) 

我想只是看看上面一定行,雖然數據,所以我增加了以下內容,它只是正常工作:

counts = histogram[0] 
xpos = histogram[1] 
ypos = histogram[2] 
image = histogram[3] 
newcounts = counts #we're going to iterate over this 

for i in range (nbins): 
    xin = xpos[i] 
    yin = ypos 
    yline = m*xin + b 
    reset = np.where(yin < yline) #anything less than yline we want to be 0 
    #index = index[0:len(index)-1] 
    countout = counts[i] 
    countout[reset] = 0 
    newcounts[i] = countout 

不過,我現在需要通過該切割區域繪製迴歸線。在plt.2dhist中這樣做是不可能的(AFAIK),所以我使用plt.scatter。問題是我不知道如何使這個切割 - 我不能索引scatterplot。

我現在有這樣的:

plt.xlim(-1,.5) 
plt.ylim(.225, .4) 

scatter = plt.scatter(fehsc,ofesc, marker = ".") 

,我只希望保留一些上面一行的數據:

xarr = np.arange(-1,0.5, 0.015) 
yarr = m*xarr + b 
plt.plot(xarr, yarr, color='r') 

我已經試過與變數,但是我的一些變化運行的環實際上並不瞭解或不知道如何使其發揮作用。

+0

所以我才正確地理解這一點,你想通過數據的一些數據的散點圖和線然後你想要刪除該行下面的所有點?或者可能以不同的顏色? –

+0

你好!您的第一個解釋是正確的 - 我希望移除該行下面的所有數據,因爲我想對該行上面的數據進行進一步分析。 –

回答

3

您可以在繪製數據之前爲數據定義mask,然後繪製實際符合條件的數據點。在一個例子中,一個特定線上方的所有數據點都以綠色繪製,並且該線下方的所有數據點都以黑色繪製。

from matplotlib import pyplot as plt 
import numpy as np 

#the scatterplot data 
xvals = np.random.rand(100) 
yvals = np.random.rand(100) 

#the line 
b = 0.1 
m = 1 
x = np.linspace(0,1,num=100) 
y = m*x+b 

mask = yvals > m*xvals+b 

plt.scatter(xvals[mask],yvals[mask],color='g') 
plt.scatter(xvals[~mask],yvals[~mask],color='k') 
plt.plot(x,y,'r') 
plt.show() 

結果看起來是這樣的scatterplot with line

希望這有助於。

EDIT

如果要創建二維直方圖,其中該線以下的部分被設置爲零,則可以做到這一點通過首先產生使用numpy直方圖(作爲數組),然後如果垃圾箱落在線下,則將該數組內的值設置爲零。在此之後,您可以使用plt.pcolormesh繪製矩陣:

from matplotlib import pyplot as plt 
import numpy as np 

#the scatterplot data 
xvals = np.random.rand(1000) 
yvals = np.random.rand(1000) 
histogram,xbins,ybins = np.histogram2d(xvals,yvals,bins=50) 

#computing the bin centers from the bin edges: 
xcenters = 0.5*(xbins[:-1]+xbins[1:]) 
ycenters = 0.5*(ybins[:-1]+ybins[1:]) 

#the line 
b = 0.1 
m = 1 
x = np.linspace(0,1,num=100) 
y = m*x+b 

#hiding the part of the histogram below the line 
xmesh,ymesh = np.meshgrid(xcenters,ycenters) 
mask = m*xmesh+b > ymesh 
histogram[mask] = 0 

#making the plot 
mat = plt.pcolormesh(xcenters,ycenters,histogram) 
line = plt.plot(x,y,'r') 
plt.xlim([0,1]) 
plt.ylim([0,1]) 
plt.show() 

其結果將是這樣的:histogram with part below line removed

+0

幫了一大堆!我已經有了2D直方圖,我只需要讓scatterplot工作。 :) –