簡體   English   中英

在輪廓上繪制點 - Matplotlib / Python

[英]Plot points over contour - Matplotlib / Python

我正在嘗試使用Matplotlib在輪廓上繪制一些點。

我有標量字段,我想從中繪制輪廓。 但是,我的ndarray的尺寸為0 x 20,但我的真實空間從-4到4不等。

我可以使用這段代碼繪制這個輪廓:

x, y = numpy.mgrid[-4:4:20*1j, -4:4:20*1j]

# Draw the scalar field level curves
cs = plt.contour(scalar_field, extent=[-4, 4, -4, 4])
plt.clabel(cs, inline=1, fontsize=10)

問題是'因為我必須在這個圖上繪制一些點,並且這些點是使用ndarray獲得的,即,我得到的點隨着這個數組維度而變化。

我嘗試使用以下代碼繪制這些點:

def plot_singularities(x_dim, y_dim, steps, scalar_field, min_points, max_points, file_path):
    """
    :param x_dim : the x dimension of the scalar field
    :param y_dim : the y dimension of the scalar field
    :param steps : the discretization of the scalar field
    :param file_path : the path to save the data
    :param scalar_field : the scalar_field to be plot
    :param min_points : a set (x, y) of min points of the scalar field
    :param max_points : a set (x, y) of max points of the scalar field
    """
    min_points_x = min_points[0]
    min_points_y = min_points[1]
    max_points_x = max_points[0]
    max_points_y = max_points[1]

    plt.figure()

    x, y = numpy.mgrid[-x_dim:x_dim:steps*1j, -y_dim:y_dim:steps*1j]

    # Draw the scalar field level curves
    cs = plt.contour(scalar_field, extent=[-x_dim, x_dim, -y_dim, y_dim])
    plt.clabel(cs, inline=1, fontsize=10)

    # Draw the min points
    plt.plot(min_points_x, min_points_y, 'ro')

    # Draw the max points
    plt.plot(max_points_x, max_points_y, 'bo')

    plt.savefig(file_path + '.png', dpi=100)
    plt.close()

但我有這個圖像:

在此輸入圖像描述

哪個不對。

如果我更改此行:

cs = plt.contour(scalar_field, extent=[-x_dim, x_dim, -y_dim, y_dim])

對於那個:

cs = plt.contour(scalar_field)

在此輸入圖像描述

我得到了所需的行為,但是范圍不顯示我的真實數據空間,而是顯示ndarray維度。

最后,如果我不繪制這些點(注釋plot()行),我可以使用我想要的范圍:

在此輸入圖像描述

但我必須繪制積分。 兩個數據都在同一個空間中。 但是contour()函數允許我指定網格。 在繪制點時我可以找到一種方法來做到這一點。

我想知道如何正確設置我想要的范圍。

先感謝您。

如果不提供與標量字段對應的xy數據,則contour使用最大為數組大小的整數值。 這就是軸顯示陣列尺寸的原因。 參數extent應給出最小和最大xy值; 我認為這就是“數據空間”的含義。 因此對contour的調用將是:

contour(scalar_field,extent=[-4,4,-4,4])

這可以通過指定xy數據來重現:

contour(numpy.linspace(-4,4,20),numpy.linspace(-4,4,20),scalar_field)

然后輪廓看起來與第一個繪圖完全一樣。 我認為這是不正確的原因,因為最小和最大點不在正確的位置。 根據您提供的信息,這是因為傳遞給函數的min_pointsmax_points是數組scalar_field 索引 ,因此它們對應於整數,而不是實際的xy值。 嘗試使用這些索引通過定義來訪問xy點:

x=numpy.linspace(-4,4,20)
y=numpy.linspace(-4,4,20)

例如,如果最小點為(0,1) ,則它對應於(x[0], y[1]) 我認為mgrid可以做類似的事情,但我自己從未使用過。

你想繪制真實數據空間中的輪廓和點,是嗎? plt.contour將獲取與您擁有的2d數組相關聯的x和y值,並將在軸上正確繪制。

xvals = -x_dim:x_dim:step  # I'm not sure about these ... but you get the idea
yvals = -y_dim:y_dim_step
plt.contour(xvals, yvals, scalar_field)

暫無
暫無

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

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