给出3分和一个情节圆

时间:2015-03-07 02:27:01

标签: python matplotlib plot

我想将点[0,1],[1,0]和[0,-1]赋予python并绘制经过它们的圆圈。存在一个python模块,使这个?我尝试过使用matplotlib:

import matplotlib.pyplot as plt
plt.plot([0,1,0],[1,0,-1])
plt.show()

但只给了我两行。

5 个答案:

答案 0 :(得分:7)

有一个"代码高尔夫"问题与此完全匹配(除了请求圆形方程,而不是绘制它) - 请参阅https://codegolf.stackexchange.com/questions/2289/circle-through-three-points。将第一个和最短的(Python)解决方案解析为更具可读性,更少hacky的形式以匹配您的确切规范 - 但保留使用复数进行简单计算的核心理念:

x, y, z = 0+1j, 1+0j, 0-1j
w = z-x
w /= y-x
c = (x-y)*(w-abs(w)**2)/2j/w.imag-x
print '(x%+.3f)^2+(y%+.3f)^2 = %.3f^2' % (c.real, c.imag, abs(c+x))

好的,这仍然是"打印等式"而不是"绘制圆圈",但是,我们正在接近:-)。要实际绘制 matplotlib中的圆圈,请参阅例如plot a circle with pyplot - 在上面的解决方案中,c是圆圈的(否定)中心(作为复数,所以使用.real和.imag作为x / y坐标),abs(c+x)半径(实数,abs使得它如此)。

答案 1 :(得分:2)

此代码还可以让您轻松地检查3个点是否形成一条线。

def define_circle(p1, p2, p3):
    """
    Returns the center and radius of the circle passing the given 3 points.
    In case the 3 points form a line, returns (None, infinity).
    """
    temp = p2[0] * p2[0] + p2[1] * p2[1]
    bc = (p1[0] * p1[0] + p1[1] * p1[1] - temp) / 2
    cd = (temp - p3[0] * p3[0] - p3[1] * p3[1]) / 2
    det = (p1[0] - p2[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p2[1])

    if abs(det) < 1.0e-6:
        return (None, np.inf)

    # Center of circle
    cx = (bc*(p2[1] - p3[1]) - cd*(p1[1] - p2[1])) / det
    cy = ((p1[0] - p2[0]) * cd - (p2[0] - p3[0]) * bc) / det

    radius = np.sqrt((cx - p1[0])**2 + (cy - p1[1])**2)
    return ((cx, cy), radius)

并解决原始问题:

center, radius = define_circle((0,1), (1,0), (0,-1))
if center is not None:
    plt.figure(figsize=(4, 4))
    circle = plt.Circle(center, radius)
    plt.gcf().gca().add_artist(circle)

(从here调整)

答案 2 :(得分:1)

非常很好奇accepted answer by Alex Martelli 的工作原理。无论如何,我必须为我的讲座创建一份报告,所以我将其粘贴在这里以供后代使用。

enter image description here enter image description here

答案 3 :(得分:0)

要在matplotlib中绘制一个圆,首先需要声明一个艺术家

circle = plt.Circle((0,0), 2)
然后,您必须将该艺术家添加到轴的实例中:

fig, ax = plt.subplots()
ax.add_artist(circle)

然后你可以安全地画它。

plt.show()

请注意,艺术家Circle获取圆圈中心的(x,y)坐标和半径r。这意味着您必须自己计算这些值。

答案 4 :(得分:0)

给出三个坐标为:

的点

(p,t)(q,u)(s,z)

......由这三个点定义的圆的等式是:

x ^ 2 + y ^ 2 + A x + B y + C = 0

其中:

A=((u-t)*z^2+(-u^2+t^2-q^2+p^2)*z+t*u^2+(-t^2+s^2-p^2)*u+(q^2-s^2)*t)/((q-p)*z+(p-s)*u+(s-q)*t)

B=-((q-p)*z^2+(p-s)*u^2+(s-q)*t^2+(q-p)*s^2+(p^2-q^2)*s+p*q^2-p^2*q)/((q-p)*z+(p-s)*u+(s-q)*t)

C=-((p*u-q*t)*z^2+(-p*u^2+q*t^2-p*q^2+p^2*q)*z+s*t*u^2+(-s*t^2+p*s^2-p^2*s)*u+(q^2*s-q*s^2)*t)/((q-p)*z+(p-s)*u+(s-q)*t)

以上是一般解决方案。您可以将A,B和C的公式放入程序中 给出3个点,找到任意圆的方程。

对于点(0,1)(1,0)(0,-1)的特定问题,您将得到:

A = 0

B = 0

C = -1

...所以等式将是

x ^ 2 + y ^ 2 -1 = 0(单位圆)