Import the libraries:
import matplotlib.pyplot as plt
import numpy as np
import math
import random
import pandas as pd
Given (x, y) coordinant, within_circle will return TRUE if the point is inside the cirle. Otherwise, the function will return FALSE.
def within_circle(x, y, radius=1, c_x=0, c_y=0):
dis = math.sqrt(((x-c_x)**2) + ((y-c_y)**2))
return dis < radius
generate_data will take size as the number of sample data that will be generate.
def generate_data(size, center_x=0, center_y=0, radius=1):
count = 0
x = []
y = []
while(count < size):
x_var = random.uniform(center_x - radius,center_x + radius)
y_var = random.uniform(center_y-radius, center_y + radius)
if(within_circle(x_var, y_var,radius, center_x, center_y)):
x.append(x_var)
y.append(y_var)
count+=1
return x, y
Generate 500 data points centered at (0, 0) with radius of 1
x, y = generate_data(1000, 0, 0, 1)
Plot the 500 data generated from generate_data function above.
plt.scatter(x, y, marker='o', color="red", s=5)
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
plt.gca().set_aspect('equal', adjustable='box')
data = {'x': x, 'y':y}
Loop through to check and assign quandrant to each point in data
q = []
for i, j in zip(x, y):
if(i > 0):
if(j>0):
q.append("I")
else:
q.append("IV")
else:
if(j>0):
q.append("II")
else:
q.append("III")
data["Quadrants"] = q
Creat pandas dataframe from with the (x, y) coordinate and its respective quadrant.
df = pd.DataFrame(data)
df
| x | y | Quadrants | |
|---|---|---|---|
| 0 | 0.804789 | -0.344615 | IV |
| 1 | 0.194384 | -0.449343 | IV |
| 2 | 0.692455 | 0.293018 | I |
| 3 | -0.654444 | -0.585161 | III |
| 4 | 0.294066 | -0.822927 | IV |
| ... | ... | ... | ... |
| 995 | 0.618112 | -0.044275 | IV |
| 996 | 0.671554 | -0.059373 | IV |
| 997 | -0.739402 | -0.244411 | III |
| 998 | 0.253110 | -0.586791 | IV |
| 999 | -0.663163 | 0.144050 | II |
1000 rows × 3 columns
Count the values of each quadrant, and then plot into piechart.
spreadness = df['Quadrants'].value_counts()
pie_data = np.array([spreadness["I"],spreadness["II"],spreadness["III"],spreadness["IV"]])
mylabels = ["Quadrant I", " Quadrant II", "Quadrant III", "Quadrant IV"]
plt.pie(pie_data, labels = mylabels, autopct='%.1f%%',)
([<matplotlib.patches.Wedge at 0x11ba52fa0>, <matplotlib.patches.Wedge at 0x11ba5e700>, <matplotlib.patches.Wedge at 0x11ba5ed90>, <matplotlib.patches.Wedge at 0x11ba69460>], [Text(0.7802572074659874, 0.7753700343689969, 'Quadrant I'), Text(-0.7899389160720414, 0.765504088085053, ' Quadrant II'), Text(-0.7530018405458982, -0.8018654676031945, 'Quadrant III'), Text(0.7875301149299792, -0.7679819777041478, 'Quadrant IV')], [Text(0.42559484043599305, 0.4229291096558165, '24.9%'), Text(-0.4308757724029316, 0.4175476844100289, '25.7%'), Text(-0.41072827666139905, -0.43738116414719697, '24.8%'), Text(0.4295618808708977, -0.4188992605658987, '24.6%')])