Skip to content

Instantly share code, notes, and snippets.

@colonialjelly
Last active April 1, 2020 15:14
Show Gist options
  • Save colonialjelly/5fa1512ed6708fb3eb80839d7dbee9e1 to your computer and use it in GitHub Desktop.
Save colonialjelly/5fa1512ed6708fb3eb80839d7dbee9e1 to your computer and use it in GitHub Desktop.
Code to generate and plot concentric circles
import numpy as np
import matplotlib.pyplot as plt
'''
Generates points on the boundaries of a circle
Args:
center (tuple): The center of the circle
radius (int): The radius of the circle
num_points (int): Number of points to generate
noise_lvl (float): The level of noise to apply to generation
Returns:
(numpy.ndarray; shape=(num_points, 2)): The generated points around the defined circle
'''
def circle(center, radius, num_points, noise_lvl):
h, k = center
theta = np.random.uniform(0, 2*np.pi, size=num_points)
x = (h + np.cos(theta) * radius) + np.random.normal(0, noise_lvl, size=num_points)
y = (k + np.sin(theta) * radius) + np.random.normal(0, noise_lvl, size=num_points)
return np.column_stack((x, y))
'''
Generates concentric circles with the provided radii
Args:
center (tuple): The center of the circles
radii (list): The radii of the circles
num_points (int): Number of points to generate for each circle
noise_lvl (float): The level of additive noise to apply to generation
Returns:
points (numpy.ndarray; shape=(num_points, 2)): The generated points that represent the concentric circles
labels (numpy.ndarray; shape=(num_points, )): The corresponding labels of the generated points
'''
def make_circles(center, radii, num_points, noise_lvl):
circles = [circle(center, r, num_points, noise_lvl) for r in radii]
points = np.vstack(circles)
labels = np.repeat(np.arange(len(radii)), num_points)
return points, labels
# Plots the concentric circles and colors them with their respective labels
def plot(points, labels, img_name=''):
fig = plt.figure(figsize=(6, 6))
plt.axes().set_aspect('equal', 'datalim')
plt.box(False)
plt.axis('off')
plt.scatter(points[:, 0], points[:, 1], c=labels, edgecolors='k', s=30, cmap=plt.cm.twilight)
plt.show()
if img_name:
fig.savefig(f'{img_name}.png')
# Input parameters
center = (0, 0)
radii = np.arange(20) * 10
num_points = 500
noise_lvl = 1
# Generate points
points, labels = make_circles(center, radii, num_points, noise_lvl)
# Plot the circles and save it as an image
plot(points, labels, 'concentric_circles')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment