Reputation: 522
Suppose I have a coordinate grid with a few points(masses) sprinkled in the grid. I can create this using:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([[0,1],[2,1],[3,5]]) # array containing the coordinates of masses(points) in the form [x,y]
x1, y1 = zip(*points)
Now, I can plot using :
plt.plot(x1,y1,'.')
Now, say I create a 2D meshgrid using:
x = np.linspace(-10,10,10)
y = np.linspace(-10,10,10)
X,Y = np.meshgrid(x,y)
Now, what I want to do is to create a 2D array 'Z',(a map of the masses)that contains masses at the locations that are in the array points. When I mean masses, I just mean a scalar at those points. So I could do something like plt.contourf(X,Y,Z). The problem I'm having is that the indices for Z cannot be the same as the coordinates in points. There has to be some sort of conversion which I'm not able to figure out. Another way to look at it is I want:
Z[X,Y] = 1
I want Z to have 1's at locations which are specified by the array points. So the essence of the problem is how do I calculate the X and Y indices such that they correspond to x1, y1 in real coordinates.
For example, if I simply do Z[x1(i),y1(i)] = 1, contourf gives this:
Instead I want the spikes to be at (0,1),(2,1),(3,5).
Upvotes: 0
Views: 2669
Reputation: 4542
To have 1 at the coordinates specified by x1, y1 and zeros everywhere else, I would write it like this:
x = np.linspace(-10, 10, 21)
y = np.linspace(-10, 10, 21)
Z = np.zeros((len(y), len(x)))
for i in range(len(x1)):
Z[10 + y1[i], 10 + x1[i]] = 1
Then you should be able to write plt.contourf(x, y, Z)
.
Tell me if that gives you the desired result.
Upvotes: 1