How to scatter plot two concentric circles with Numpy and Matplotlib

Question:

I’m trying to recreate the following plot with Numpy and Matplotlib as part of a question, but I’m struggling to get the "random aspect" of the plot:

this plot

I’ve already managed to create the two circles and plot them with this code:

import numpy as np
import matplotlib.pyplot as plt

r = [5, 10]
angle = np.linspace(0, 2 * np.pi, 100)

X = [r[0] * np.cos(angle), r[1] * np.cos(angle)]
Y = [r[0] * np.sin(angle), r[1] * np.sin(angle)]

plt.axis('equal');
plt.scatter(X[0], Y[0], c='purple');
plt.scatter(X[1], Y[1], c='yellow');

But I don’t know how to make them get this random scattering, like in the example image. I know I need to use Numpy’s random number generation, but I don’t know how or where to use it, exactly.

Asked By: Wesley Alves

||

Answers:

You might need more than 100 points, so let’s say

t = np.linspace(0, 2 * np.pi, 1000, endpoint=False)

You have the right idea regarding how to build a circle, so add a random radius to each point:

r = np.random.uniform([[4], [9]], [[6], [11]], size=(2, 1000))

This is not necessarily the best way to do it, since the points will be biased towards the center, but it suffices to illustrate the idea.

plt.scatter(r[0] * np.cos(t), r[0] * np.sin(t))
plt.scatter(r[1] * np.cos(t), r[1] * np.sin(t))

On second inspection of your images, you may want to replace np.random.uniform with np.random.normal with a standard deviation of 1.

Answered By: Mad Physicist

You just have to add randomness to the radius (on limits set by the user).

import numpy as np
import matplotlib.pyplot as plt


# r_start = [5, 10]   make the radius random (any distribution)
r = np.random.uniform([[4.5], [9.5]], [[5.5], [10.5]], size=(2, 100))
angle = np.linspace(0, 2 * np.pi , 100 )

X = [r[0] * np.cos(angle), r[1] * np.cos(angle)]
Y = [r[0] * np.sin(angle), r[1] * np.sin(angle)]

plt.axis('equal')
plt.scatter(X[0], Y[0], c='purple')
plt.scatter(X[1], Y[1], c='yellow')
plt.show()

example output:

enter image description here

Answered By: D.L