简体   繁体   中英

Creating a 2D array using values of coordinate points on a grid

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). 在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM