2017-05-19 98 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工作。 :) –