Python 用 matplotlib 绘制方程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14000595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:09:22  来源:igfitidea点击:

graphing an equation with matplotlib

pythonmatplotlib

提问by ?then?

I'm trying to make a function that will graph whatever formula I tell it to.

我正在尝试制作一个函数来绘制我告诉它的任何公式。

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = formula  
    plt.plot(x, y)  
    plt.show()  

When I try to call it the following error happens, I believe it's trying to do the multiplication before it gets to y = formula.

当我尝试调用它时会发生以下错误,我相信它正在尝试在乘法之前进行乘法运算y = formula

graph(x**3+2*x-4, range(-10, 11))

Traceback (most recent call last):  
  File "<pyshell#23>", line 1, in <module>  
    graph(x**3+2*x-4, range(-10, 11))  
NameError: name 'x' is not defined  

采纳答案by rputikar

This is because in line

这是因为在线

graph(x**3+2*x-4, range(-10, 11))

x is not defined.

x 未定义。

The easiest way is to pass the function you want to plot as a string and use evalto evaluate it as an expression.

最简单的方法是将要绘制的函数作为字符串传递并用于eval将其作为表达式求值。

So your code with minimal modifications will be

所以你的代码修改最少

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = eval(formula)
    plt.plot(x, y)  
    plt.show()

and you can call it as

你可以称之为

graph('x**3+2*x-4', range(-10, 11))

回答by DSM

Your guess is right: the code is trying to evaluate x**3+2*x-4immediately. Unfortunately you can't really prevent it from doing so. The good news is that in Python, functions are first-class objects, by which I mean that you can treat them like any other variable. So to fix your function, we could do:

您的猜测是正确的:代码正在尝试x**3+2*x-4立即评估。不幸的是,您无法真正阻止它这样做。好消息是,在 Python 中,函数是一等对象,我的意思是你可以像对待任何其他变量一样对待它们。因此,要修复您的功能,我们可以这样做:

import numpy as np  
import matplotlib.pyplot as plt  

def graph(formula, x_range):  
    x = np.array(x_range)  
    y = formula(x)  # <- note now we're calling the function 'formula' with x
    plt.plot(x, y)  
    plt.show()  

def my_formula(x):
    return x**3+2*x-4

graph(my_formula, range(-10, 11))

If you wanted to do it all in one line, you could use what's called a lambdafunction, which is just a short function without a name where you don't use defor return:

如果您想在一行中完成所有操作,您可以使用所谓的lambda函数,它只是一个没有名称的简短函数,您不使用defor return

graph(lambda x: x**3+2*x-4, range(-10, 11))

And instead of range, you can look at np.arange(which allows for non-integer increments), and np.linspace, which allows you to specify the start, stop, and the number of points to use.

而不是range,您可以查看np.arange(允许非整数增量)和np.linspace,它允许您指定开始、停止和要使用的点数。

回答by jelde015

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

要绘制未针对特定变量(如圆或双曲线)求解的方程:

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

更多相关信息:http: //courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf