在轮廓上绘制点-Matplotlib / Python

pce*_*con 5 python plot matplotlib

我正在尝试使用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)
Run Code Online (Sandbox Code Playgroud)

问题是,因为我必须在该图上绘制一些点,并且这些点是使用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()
Run Code Online (Sandbox Code Playgroud)

但是我得到了这张图片:

在此处输入图片说明

这是不正确的。

如果我更改此行:

cs = plt.contour(scalar_field, extent=[-x_dim, x_dim, -y_dim, y_dim])
Run Code Online (Sandbox Code Playgroud)

对于那个:

cs = plt.contour(scalar_field)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我得到了想要的行为,但是范围并没有显示我的实际数据空间,而是ndarray维。

最后,如果不绘制这些点(注释plot()线),则可以扩展所需的范围:

在此处输入图片说明

但是我必须画点。两种数据都在同一空间中。但是轮廓()函数允许我指定网格。在绘制点时,我可以找到一种方法来执行此操作。

如何正确设置范围?

amd*_*amd 5

如果您不提供xy标量字段对应的数据,contour则使用最大为数组大小的整数值。这就是轴显示数组维度的原因。参数extent应给出最小值、最大值xy值;我认为这就是您所说的“数据空间”。所以调用contour将是:

contour(scalar_field,extent=[-4,4,-4,4])
Run Code Online (Sandbox Code Playgroud)

这可以通过指定xy数据来重现:

contour(numpy.linspace(-4,4,20),numpy.linspace(-4,4,20),scalar_field)
Run Code Online (Sandbox Code Playgroud)

然后轮廓看起来与您的第一个图中完全相同。我认为这是不正确的原因是最小点和最大点不在正确的位置。根据您提供的信息,这是因为您传递给函数min_points的 和是array 的索引,因此它们对应于整数,而不是实际的和值。尝试通过定义使用这些索引来访问和点:max_pointsscalar_fieldxyxy

x=numpy.linspace(-4,4,20)
y=numpy.linspace(-4,4,20)
Run Code Online (Sandbox Code Playgroud)

例如,如果最小点为(0,1),则它将对应于(x[0], y[1])。我认为可以用 来完成类似的事情mgrid,但我自己从未使用过。