簡體   English   中英

matplotlib 2D數據切片

[英]matplotlib 2D slice of 3D data

我無法找到任何相關內容,也許是因為我沒有正確的命名法(即我不確切知道如何要求它),但無論如何,我有一個3D numpy數組“a”。 我想識別並繪制a = 0的2D表面。 為了清楚起見,數據是雙精度浮點數在3D空間中平滑變化。 表面a = 0很可能會“穿過”陣列的點之間,而不是恰好位於它們中的任何一個上。 所以我需要一些可以插值來找到a = 0表面並繪制它的東西。 matplotlib是否有這樣做的現成例程?

使用Plotly,您可以在體積數據中繪制平面和非線性切片: http//nbviewer.jupyter.org/github/empet/Plotly-plots/blob/master/Plotly-Slice-in-volumetric-data.ipynb

要“識別並繪制a = 0的2D表面”,你只需要將數據子集a=0和繪圖(如下所示)如果你正在尋找數據投影到那個平面上,那么這就是一點點更復雜。

threeD = np.array([(x,y,z) for x in [0,1] for y in [1,2] for z in [5,6]])
twoD = np.array([(y,z) for (x,y,z) in threeD if x==0])
y,z = zip(*twoD)
plt.plot(y,z, 'o')
plt.xlim(0,3)
plt.ylim(0,7)

在此輸入圖像描述

體積切片操作通常依賴於插值的概念,最典型的是: 最近鄰線性立方 請注意,這些方法適用於更多維數(例如參見雙線性三線性插值)。

在這種情況下,你說你有一個卷,你可以從中檢索X,Y,Z(或混合,但不考慮這種情況,因為它是一個新的整體問題,只會帶來混亂)。

因此,例如,考慮切片X = 5和X = 6,您想知道如何獲得X = 5.5。 看看這個例子:

def linear_interpolation(p1, p2, x0):
    """
    Function that receives as arguments the coordinates of two points (x,y)
    and returns the linear interpolation of a y0 in a given x0 position. This is the
    equivalent to obtaining y0 = y1 + (y2 - y1)*((x0-x1)/(x2-x1)).
    Look into https://en.wikipedia.org/wiki/Linear_interpolation for more
    information.

    Parameters
    ----------
    p1     : tuple (floats)
        Tuple (x,y) of a first point in a line.
    p2     : tuple (floats)
        Tuple (x,y) of a second point in a line.
    x0     : float
        X coordinate on which you want to interpolate a y0.

    Return float (interpolated y0 value)
    """
    return p1[1] + (p2[1] - p1[1]) * ((x0 - p1[0]) / (p2[0] - p1[0]))

X, Y, Z = np.meshgrid(range(10), range(10), range(10))
vol = np.sqrt((X-5)**2 + (Y-5)**2 + (Z-5)**2)

Slice5dot5 = linear_interpolation((Y[5, :, :], vol[5, :, :]), (Y[6, :, :], vol[6, :, :]), 5.5)

f, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True)
ax1.imshow(vol[5, :, :], interpolation='nearest', origin='lower', vmin=vol.min(), vmax=vol.max())
ax1.set_title("vol[5, :, :]")
ax2.imshow(Slice5dot5, interpolation='nearest', origin='lower', vmin=vol.min(), vmax=vol.max())
ax2.set_title("vol[5.5, :, :]")
ax3.imshow(vol[6, :, :], interpolation='nearest', origin='lower', vmin=vol.min(), vmax=vol.max())
ax3.set_title("vol[6, :, :]")
plt.show()

該函數出現在文檔中(它是我做過的一個舊項目的一部分)與數字一起使用,但它與numpy 2D切片一樣好(並且它比循環所有這些單元要快得多)。

結果如下:

卷切片matplotlib

你會注意到顏色從左到右變得蒼白。 中間的切片是完全插值的,之前不存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM