2017-09-26 140 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