Matplotlib 在散点图中连接点

Matplotlib 在散点图中连接点,matplotlib,Matplotlib,我有一个散点图,看起来像一个圆。我想用一条线连接外部点,以显示几乎圆形的形状。在matplotlib中有这样做的方法吗?您可以使用fromscipy.spatial查找散点图的外部点,然后使用frommatplotlib.collections将这些点连接起来: from matplotlib import pyplot as plt import numpy as np from scipy.spatial import ConvexHull from matplotlib.collectio

我有一个散点图,看起来像一个圆。我想用一条线连接外部点,以显示几乎圆形的形状。在matplotlib中有这样做的方法吗?

您可以使用from
scipy.spatial
查找散点图的外部点,然后使用from
matplotlib.collections将这些点连接起来:

from matplotlib import pyplot as plt
import numpy as np
from scipy.spatial import ConvexHull
from matplotlib.collections import PolyCollection


fig, ax = plt.subplots()

length = 1000

#using some normally distributed data as example:
x = np.random.normal(0, 1, length)
y = np.random.normal(0, 1, length)

points = np.concatenate([x,y]).reshape((2,length)).T
hull = ConvexHull(points)



ax.scatter(x,y)

ax.add_collection(PolyCollection(
    [points[hull.vertices,:]],
    edgecolors='r',
    facecolors='w',
    linewidths=2,
    zorder=-1,
    ))



plt.show()
结果如下所示:

编辑

实际上,您可以跳过多边形集合,只需使用外壳顶点进行简单的线打印。只需通过将第一个顶点附加到顶点列表中(使该列表中的一个元素变长)使线成为圆形即可:

编辑2

我注意到,在中有一个例子看起来与我的非常相似

您可以使用from
scipy.spatial
查找散点图的外部点,然后使用from
matplotlib.collections连接这些点:

from matplotlib import pyplot as plt
import numpy as np
from scipy.spatial import ConvexHull
from matplotlib.collections import PolyCollection


fig, ax = plt.subplots()

length = 1000

#using some normally distributed data as example:
x = np.random.normal(0, 1, length)
y = np.random.normal(0, 1, length)

points = np.concatenate([x,y]).reshape((2,length)).T
hull = ConvexHull(points)



ax.scatter(x,y)

ax.add_collection(PolyCollection(
    [points[hull.vertices,:]],
    edgecolors='r',
    facecolors='w',
    linewidths=2,
    zorder=-1,
    ))



plt.show()
结果如下所示:

编辑

实际上,您可以跳过多边形集合,只需使用外壳顶点进行简单的线打印。只需通过将第一个顶点附加到顶点列表中(使该列表中的一个元素变长)使线成为圆形即可:

编辑2


我注意到,在中有一个例子看起来与我的非常相似

呜呜,呜呜,呜呜,呜呜