我正在尝试使用 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() 函数允许我指定网格。 在绘制点时,我可以找到一种方法来执行此操作。
如何正确设置范围?
最佳答案
如果您不提供 x
和 y
与标量场对应的数据,contour
使用不超过数组大小的整数值。这就是轴显示数组维度的原因。参数extent
应该给出最小值和最大值 x
和 y
值(value)观;我假设这就是您所说的“数据空间”。所以调用contour
会是:
contour(scalar_field,extent=[-4,4,-4,4])
这可以通过指定 x
来复制和 y
数据:
contour(numpy.linspace(-4,4,20),numpy.linspace(-4,4,20),scalar_field)
然后轮廓看起来与您的第一个图中完全一样。我假设这是不正确的原因,因为最小点和最大点不在正确的位置。根据您提供的信息,这是因为 min_points
和 max_points
您传递给函数的是数组 scalar_field
的索引 , 所以它们对应于整数,而不是实际的 x
和 y
值。尝试使用这些索引来访问 x
和 y
通过定义点:
x=numpy.linspace(-4,4,20)
y=numpy.linspace(-4,4,20)
例如,如果您的最小积分为 (0,1)
, 它将对应于 (x[0], y[1])
.我认为可以用 mgrid
做类似的事情。 ,但我自己从未使用过。
关于python - 在轮廓上绘制点 - Matplotlib/Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24707441/