简体   繁体   中英

Broadcasting columns from a 2D numpy array to a larger 2D array based on an array of floats

I'm not quite sure how to say this so I'll try to be clear in my description. Right now I have a 3D numpy array where the 1st column represents a depth and the 2nd a position on the x-axis. My goal is to make a pcolor where the columns are spread out along the x-axis based on the values in a 1D float array.

Here's where it gets tricky, I only have the relative distances between points. That is, the distance between column 1 and column 2 and so on.

Here's an example of what I have and what I'd like:

darray = [[2  3  7  7]
          [4  8  2  3]
          [6  1  9  5]
          [3  4  8  4]]

posarray = [ 3.767, 1.85, 0.762]

DesiredArray = [[2  0  0  0  3  0  7  7]
                [4  0  0  0  8  0  2  3]
                [6  0  0  0  1  0  9  5]
                [3  0  0  0  4  0  8  4]]

How I tried implementing it:

def space_set(darr, sarr):
    spaced = np.zeros((260,1+int(sum(sarr))), dtype = float)
    x = 0
    for point in range(len(sarr)):
            spaced[:, x] = darr[:,point]
            x = int(sum(sarr[0:point]))
    spaced[:,-1] = darr[:,-1]

Then I was planning on using matplotlibs pcolor to plot it. This method seems to lose columns though. Any ideas for either directly plotting or making a numpy array to plot? Thanks in advance.

Here's an example of what I'm looking for. 示例图片

Since there is so much whitespace, perhaps it would be easier to draw the Rectangles , rather than use pcolor . As a bonus, you can place the rectangles exactly where you want them, rather than having to "snap" them to an integer-valued grid. And, you do not have to allocate space for a larger 2D array mainly filled with zeros. (In your case the memory required is probably measly, but the idea does not scale well, so it is nice if we can avoid doing that.)

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
import matplotlib.cm as cm

def draw_rect(x, y, z):
    rect = patches.Rectangle((x,y), 1, 1, color = jet(z))
    ax.add_patch(rect)

jet = plt.get_cmap('jet')
fig = plt.figure()
ax = fig.add_subplot(111)

darray = np.array([[2, 3, 7, 7],
                   [4, 8, 2, 3],
                   [6, 1, 9, 5],
                   [3, 4, 8, 4]], dtype = 'float')
darray_norm = darray/darray.max()

posarray = [3.767, 1.85, 0.762]
x = np.cumsum(np.hstack((0, np.array(posarray)+1)))

for j, i in np.ndindex(darray.shape):
    draw_rect(x[j], i, darray_norm[i, j])
ax.set_xlim(x.min(),x.max()+1)
ax.set_ylim(0,len(darray))
ax.invert_yaxis()    
m = cm.ScalarMappable(cmap = jet)
m.set_array(darray)
plt.colorbar(m)
plt.show()

yields

在此输入图像描述

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