2017-06-15 108 views
1

如何在散点图中包围不同的数据集?如何在散点图中包围不同的数据集?

我正在寻找的是这样的:

encircle different data sets in scatter plot

而且,我怎么填写后与(阴影)颜色的圈?

+0

这个问题不是我不清楚,但https://stackoverflow.com/questions/17553035/draw-a-smooth-polygon-around-data-points-in的副本-a-scatter-plot-in-matplotlib – Florian

回答

1

您可以通过凸包scipy.spatial.ConvexHull获得所有点的穿透路径。

import matplotlib.pyplot as plt 
import numpy as np; np.random.seed(1) 
from scipy.spatial import ConvexHull 

x1, y1 = np.random.normal(loc=5, scale=2, size=(2,15)) 
x2, y2 = np.random.normal(loc=8, scale=2.5, size=(2,13)) 

plt.scatter(x1, y1) 
plt.scatter(x2, y2) 

def encircle(x,y, ax=None, **kw): 
    if not ax: ax=plt.gca() 
    p = np.c_[x,y] 
    hull = ConvexHull(p) 
    poly = plt.Polygon(p[hull.vertices,:], **kw) 
    ax.add_patch(poly) 

encircle(x1, y1, ec="k", fc="gold", alpha=0.2) 
encircle(x2, y2, ec="orange", fc="none") 

plt.show() 

enter image description here

另一种选择是周围画点云的平均一圈。

import matplotlib.pyplot as plt 
import numpy as np; np.random.seed(1) 
from scipy.spatial import ConvexHull 

x1, y1 = np.random.normal(loc=5, scale=2, size=(2,15)) 
x2, y2 = np.random.normal(loc=8, scale=2.5, size=(2,13)) 

plt.scatter(x1, y1) 
plt.scatter(x2, y2) 


def encircle2(x,y, ax=None, **kw): 
    if not ax: ax=plt.gca() 
    p = np.c_[x,y] 
    mean = np.mean(p, axis=0) 
    d = p-mean 
    r = np.max(np.sqrt(d[:,0]**2+d[:,1]**2)) 
    circ = plt.Circle(mean, radius=1.05*r,**kw) 
    ax.add_patch(circ) 

encircle2(x1, y1, ec="k", fc="gold", alpha=0.2) 
encircle2(x2, y2, ec="orange", fc="none") 

plt.gca().relim() 
plt.gca().autoscale_view() 
plt.show() 

enter image description here

+0

非常感谢:) –

相关问题