使用matplotlib在图中绘制圆圈

时间:2014-09-14 08:18:09

标签: python matplotlib

我有一个图表,现​​在我需要一个圆圈,对于y等于零的每个点。图形工作正常,但圆圈(if语句中的代码)给出错误:

import numpy as np
import matplotlib.pyplot as plt


def graph(formula, x_range):
    x = np.array(x_range)
    y = formula(x)  # <-----
    #if x == y:
    if y == 0:
        circle2=plt.Circle((x,y),.2,color='b')
        fig = plt.gcf()
        fig.gca().add_artist(circle2)
        plt.show()
    plt.plot(x, y, 'r--')
    plt.show()

graph(lambda x: (x+2) * (x-1) * (x-2), range(-3,3))

1 个答案:

答案 0 :(得分:1)

您正在传递数组xy。传递单个值。

def graph(formula, x_range):
    x = np.array(x_range)
    y = formula(x)
    for x0, y0 in zip(x, y):
        if y0 == 0:
            circle2 = plt.Circle((x0, y0), 0.1, color='b')  # <------
            fig = plt.gcf()
            fig.gca().add_artist(circle2)
    plt.plot(x, y, 'r--')
    plt.show()