Skip to content
Advertisement

How to scatter plot two concentric circles with Numpy and Matplotlib

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement