2

circle があるとしx**2 + y**2 = 20ます。n_dotsここで、散布図の円の周囲にあるドットの数で円をプロットしたいと思います。そこで、以下のようなコードを作成しました。

n_dots = 200
x1 = np.random.uniform(-20, 20, n_dots//2)
y1_1 = (400 - x1**2)**.5
y1_2 = -(400 - x1**2)**.5
plt.figure(figsize=(8, 8))
plt.scatter(x1, y1_1, c = 'blue')
plt.scatter(x1, y1_2, c = 'blue')
plt.show()

しかし、これはドットが円内のすべての場所に均一に分布していないことを示しています. 出力は次のとおりです。

出力散布図

では、円の周囲にすべての点が均一に分布している散布図で、点のある円を作成するにはどうすればよいでしょうか?

4

2 に答える 2

3

円の周囲に沿って等間隔の点をプロットする簡単な方法は、円全体を均等に小さな角度に分割することから始まり、円の中心からすべての点までの角度が取得されます。次に、各点の座標 (x,y) を計算できます。タスクを実行するコードは次のとおりです。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(8, 8))

n_dots = 120   # set number of dots
angs = np.linspace(0, 2*np.pi, n_dots)  # angles to the dots
cx, cy = (50, 20)  # center of circle
xs, ys = [], []    # for coordinates of points to plot
ra = 20.0          # radius of circle

for ang in angs:
    # compute (x,y) for each point
    x = cx + ra*np.cos(ang)
    y = cy + ra*np.sin(ang)
    xs.append(x)   # collect x
    ys.append(y)   # collect y

plt.scatter(xs, ys, c = 'red', s=5)  # plot points 
plt.show()

結果のプロット: ここに画像の説明を入力

別の方法として、numpy のブロードキャスト機能を使用してコードを短縮することもできます。

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure(figsize=(8, 8))

n_dots = 120   # set number of dots
angs = np.linspace(0, 2*np.pi, n_dots)  # angles to the dots
cx, cy = (50, 20)  # center of circle
ra = 20.0          # radius of circle

# with numpy's broadcasting feature...
# no need to do loop computation as in above version
xs = cx + ra*np.cos(angs)
ys = cy + ra*np.sin(angs)

plt.scatter(xs, ys, c = 'red', s=5)  # plot points 
plt.show()
于 2018-06-20T08:58:40.747 に答える