I am trying to generate random points uniformly distributed over rectangular region centered at (0,0) using numpy and matplotlib.
Asked
Active
Viewed 1,049 times
0
-
1meshgrid is made exactly for this purpose. https://stackoverflow.com/questions/36013063/what-is-the-purpose-of-meshgrid-in-python-numpy – Ananda Jan 28 '21 at 05:44
-
1`np.random.uniform(-20, 20, size=(1000, 2))` would generate 1000 random xy locations in the range `-20,20`. – JohanC Jan 28 '21 at 05:48
2 Answers
1
The words, random points uniformly distributed is not easy to interprete. This is one of my interpretation shown as a runnable code. Sample output plot is also given.
import matplotlib.pyplot as plt
import numpy as np
# create array of meshgrid over a rectangular region
# range of x: -cn/2, cn/2
# range of y: -rn/2, rn/2
cn, rn = 10, 14 # number of columns/rows
xs = np.linspace(-cn/2, cn/2, cn)
ys = np.linspace(-rn/2, rn/2, rn)
# meshgrid will give regular array-like located points
Xs, Ys = np.meshgrid(xs, ys) #shape: rn x cn
# create some uncertainties to add as random effects to the meshgrid
mean = (0, 0)
varx, vary = 0.007, 0.008 # adjust these number to suit your need
cov = [[varx, 0], [0, vary]]
uncerts = np.random.multivariate_normal(mean, cov, (rn, cn))
# plot the random-like meshgrid
plt.scatter(Xs+uncerts[:,:,0], Ys+uncerts[:,:,1], color='b');
plt.gca().set_aspect('equal')
plt.show()
You can change the values of varx and vary to change the level of randomness of the dot array on the plot.
swatchai
- 14,086
- 3
- 34
- 51
0
As @JohanC mentioned in comments, you need points with x and y coordinates between -20 and 20. To create them use:
np.random.uniform(-20, 20, size=(n,2))
with n being your desired number of points.
To plot them:
import matplotlib.pyplot as plt
plt.scatter(a[:,0],a[:,1])
sample plot for n=100 points:
Ehsan
- 11,523
- 2
- 17
- 30