mercredi 20 juillet 2016

How does one use numpy's Meshgrid function with a random interval rather than a equally spaced one?

Conceptually this is sort of what I wanted to do. I wanted to select random points in a 2D plane and then plot a surface plot of how that would look like. Similarly, an alternative (sub-optimal idea) could be to grade a Meshgrid and select N random points and their corresponding heights and then plot them in a surface plot.

Currently the only successful way that I've been able to make surface plots is with equally intervaled points using the following:

start_val, end_val = -1,1
N = 100
x_range = np.linspace(start_val, end_val, N)
y_range = np.linspace(start_val, end_val, N)
(X,Y) = np.meshgrid(x_range, y_range)
Z = np.sin(2*np.pi*X) + 4*np.power(Y - 0.5, 2) #function height for the sake of an example

and then plot the thing with the standard:

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm)
plt.title('Original function')

plt.show()

this results in a pretty plot of the function just as I expected.

However, I'd like to select random points in a known interval. For that I tried the alternative:

start_val, end_val = -1,1
N = 100
x_range = np.random.uniform(low=start_val, high=end_val, size=N)
y_range = np.random.uniform(low=start_val, high=end_val, size=N)
(X,Y) = np.meshgrid(x_range, y_range)
Z = np.sin(2*np.pi*X) + 4*np.power(Y - 0.5, 2) #function height for the sake of an example

Unfortunately, that results in non-sense:

enter image description here

instead of something nicer as the original with the evenly spaced points:

enter image description here

does someone know how to do the task (or a similar task) I am trying to do but being able to plot random points or include some randomness in a sensible way?




Aucun commentaire:

Enregistrer un commentaire