2017-09-26 104 views
1

我想要在x,y散点图上生成随机点,它们位于给定行的上方或下方。例如,如果该行是y = x,我想在图的左上方(图的上方)生成一个点列表,并在图的右下方(图的下方)生成一个点列表。这里的是一个示例,其中点高于或低于Y = 5:在Python中上下生成随机点

import random 
import matplotlib.pyplot as plt 

num_points = 10 
x1 = [random.randrange(start=1, stop=9) for i in range(num_points)] 
x2 = [random.randrange(start=1, stop=9) for i in range(num_points)] 
y1 = [random.randrange(start=1, stop=5) for i in range(num_points)] 
y2 = [random.randrange(start=6, stop=9) for i in range(num_points)] 

plt.scatter(x1, y1, c='blue') 
plt.scatter(x2, y2, c='red') 
plt.show() 

Random point plot

然而,我独立地产生的x和y分,这限制了我等式,其中Y = C(其中,c是一个常数)。我怎样才能扩展到任何y = mx + b?

+0

撇开你希望的实际分配的问题,因为你正在生成的X和Y坐标分开,不能你刚才生成的X坐标,然后计算每个范围相应的y坐标使用你的约束? – jq170727

回答

1

可以更改停止和启动极限y1y2是你想要的线路。您需要确定飞机在哪里结束(设置lowerupper)。

注意这只适用于整数。如果您想要更复杂的东西,可以使用截断的多变量分布。

m, b = 1, 0 
lower, upper = -25, 25 

x1 = [random.randrange(start=1, stop=9) for i in range(num_points)] 
x2 = [random.randrange(start=1, stop=9) for i in range(num_points)] 

y1 = [random.randrange(start=lower, stop=m*x+b) for x in x1] 
y2 = [random.randrange(start=m*x+b, stop=upper) for x in x2] 

plt.plot(np.arange(10), m*np.arange(10)+b) 
plt.scatter(x1, y1, c='blue') 
plt.scatter(x2, y2, c='red') 
的(X,Y)

enter image description here

1

可能有很多方法,但如果您的唯一要求是它们高于和低于y = mx + b线,那么您可以简单地将随机x值插入等式中,然后添加或减去随机y值。

import random 
import matplotlib.pyplot as plt 

slope = 1 
intercept = 0 

def ymxb(slope, intercept, x): 
    return slope * x + intercept 

num_points = 10 
x1 = [random.randrange(start=1, stop=9) for i in range(num_points)] 
x2 = [random.randrange(start=1, stop=9) for i in range(num_points)] 
y1 = [ymxb(slope, intercept, x) - random.randrange(start=1, stop=9) for x in x1] 
y2 = [ymxb(slope, intercept, x) + random.randrange(start=1, stop=9) for x in x2] 

plt.scatter(x1, y1, c='blue') 
plt.scatter(x2, y2, c='red') 
plt.show() 

,看起来像这样:

enter image description here

0

侧通过的y - mx - b符号限定。例如,您可以阅读它here

import random 
import matplotlib.pyplot as plt 

num_points = 50 
x = [random.randrange(start=1, stop=9) for i in range(num_points)] 
y = [random.randrange(start=1, stop=9) for i in range(num_points)] 
m = 5 
b = -3 

colors = ['blue' if y[i] - m * x[i] - b > 0 else 'red' for i in range(num_points) ] 
plt.plot([0, 10], [b, 10 * m + b], c='green') 
plt.xlim((0, 10)) 
plt.ylim((0, 10)) 

plt.scatter(x, y, c=colors) 
plt.show() 

enter image description here

1

您可能也有我的答案了。

这种方式使高斯噪声在线以上,以下。我故意将噪声的平均值设置为20,以便它从该线突出,即y = 10 * x + 5。您可能会使平均值为零。

>>> import random 
>>> def y(x, m, b): 
...  return m*x + b 
... 
>>> import numpy as np 
>>> X = np.linspace(0, 10, 100) 
>>> y_above = [y(x, 10, 5) + abs(random.gauss(20,5)) for x in X] 
>>> y_below = [y(x, 10, 5) - abs(random.gauss(20,5)) for x in X] 
>>> import matplotlib.pyplot as plt 
>>> plt.scatter(X, y_below, c='g') 
>>> plt.scatter(X, y_above, c='r') 
>>> plt.show() 

这里是情节。

scatter plot