[英]Broadcasting columns from a 2D numpy array to a larger 2D array based on an array of floats
我不太清楚如何這樣說,所以我會盡量在我的描述中說清楚。 現在我有一個3D numpy數組,其中第1列代表深度,第2列代表x軸。 我的目標是根據1D浮點數組中的值,在x軸上展開列。
這是它變得棘手的地方,我只有點之間的相對距離。 也就是說,列1和列2之間的距離等等。
這是我擁有的和我想要的一個例子:
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]]
我是如何嘗試實現它的:
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]
然后我計划使用matplotlibs pcolor繪制它。 這種方法似乎失去了列。 有關直接繪制或制作numpy數組的想法嗎? 提前致謝。
這是我正在尋找的一個例子。
由於有太多的空白,也許繪制矩形更容易,而不是使用pcolor 。 作為獎勵,您可以將矩形准確放置在您想要的位置,而不必將它們“捕捉”到整數值網格。 並且,您不必為主要填充零的較大2D陣列分配空間。 (在你的情況下,所需的內存可能是微不足道的,但這個想法不能很好地擴展,所以如果我們可以避免這樣做,那就太好了。)
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()
產量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.