【问题标题】:Defining an ellipse around data points在数据点周围定义一个椭圆
【发布时间】:2015-05-08 14:50:07
【问题描述】:

我有一个不知道该怎么做的问题/想法。

我有一个 X 与 Y 的散点图

我可以画一个矩形,然后选取其中的所有点。

理想情况下,我想定义一个椭圆,因为它可以更好地捕捉形状并排除它之外的所有点。

如何做到这一点?有可能吗?我使用 matplotlib 绘制了情节。

我使用线性回归 (LR) 来拟合这些点,但这并不是我真正想要的。 我想定义一个椭圆来覆盖其中尽可能多的点,然后排除它之外的点。我如何定义一个方程式/代码来选择里面的那些?

【问题讨论】:

  • 你的意思是什么?我看不出您是如何使用线性回归来绘制矩形的?
  • 可以看这里的可拖动矩形演示:matplotlib.org/1.4.0/users/…
  • 好吧,我不知道实现起来有多么困难,但是一些Data Mining 算法将满足您的需求。看看k-means算法或GMM(高斯模型)。
  • 您有数据,还是只是在戳图表?使用函数和列表理解会很容易。
  • 我确实有一个 Y=mx+b 函数并使用 numpy 数组绘制了原始数据。

标签: python matplotlib graph scatter


【解决方案1】:

如果您有图表中表示的数据结构,则可以使用函数和列表推导来完成。

如果您有这样的列表中的数据:

# Made up data
lst = [
    # First element is X, second is Y.
    (0,0),
    (92,20),
    (10,0),
    (13,40),
    (27,31),
    (.5,.5),
]

def shape_bounds(x):
    """
    Function that returns lower and upper bounds for y based on x

    Using a circle as an example here.
    """
    r = 4
    # A circle is x**2 + y**2 = r**2, r = radius
    if -r <= x <= r:
        y = sqrt(r**2-x**2)
        return -y, y
    else:
        return 1, -1 # Remember, returns lower, upper.  
        # This will fail any lower < x < upper test.        

def in_shape(elt):
    """
    Unpacks a pair and tests if y is inside the shape bounds given by x
    """
    x, y = elt
    lower_bound, upper_bound = shape_bounds(x)
    if lower_bound < y < upper_bound:
        return True
    else:
        return False

# Demo walkthrough
for elt in lst:
    x, y = elt
    print x, y
    lower_bound, upper_bound = shape_bounds(x)
    if lower_bound < y < upper_bound:
        print "X: {0}, Y: {1} is in the circle".format(x, y)

# New list of only points inside the shape
new_lst = [x for x in lst if in_shape(x)]

至于椭圆,尝试根据this改变形状方程

【讨论】:

    猜你喜欢
    • 2015-08-21
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2017-03-18
    相关资源
    最近更新 更多