简体   繁体   English

如何使用matplotlib在函数图上绘制点?

[英]How to plot points on a graph of a function with matplotlib?

I have 我有

def f(x):
    return (x**2 / 10) - 2 * np.sin(x)


def plot_fn():
    x = np.arange(-10, 10, 0.1)
    fn = f(x)

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    # Move left y-axis and bottim x-axis to centre, passing through (0,0)
    ax.spines['left'].set_position('center')
    ax.spines['bottom'].set_position('center')

    # Eliminate upper and right axes
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')

    # Show ticks in the left and lower axes only
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    plt.plot(x, fn)
    plt.show()

I also want to plot some points on the graph as well. 我也想在图表上绘制一些点。 For example, when x is 0, then the y is -4.49. 例如,当x为0时,则y为-4.49。 So I want to plot a list of x,y points. 因此,我想绘制x,y点的列表。 How can I do this on the same plot? 如何在同一地块上进行此操作?

You can add the points in the function call arguments: 您可以在函数调用参数中添加点:

def plot_fn(xpoints=None, ypoints=None):
   #...your code before plt.show
   if x is not None:
       ax.plot(x_points , y_points, 'go')
   plt.show()

plot_fn([0], [-4.99])

If you want to be able to add the additional points later after plotting the curve in the function, you can return the axis instance from the figure and then use it later to plot. 如果要在函数中绘制曲线后稍后再添加其他点,可以从图中返回轴实例,然后在以后使用它进行绘制。 Following code explains it 以下代码对此进行了解释

def plot_fn():
    x = np.arange(-10, 10, 0.1)
    fn = f(x)

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    # Your spines related code here
    # ........

    ax.plot(x, fn)
    return ax

ax_ = plot_fn()

x_data = [0, 1]
y_data = [-4.49, 3.12]
ax_.scatter(x_data, y_data, c='r')
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM