## 如何用matplotlib绘制方程？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (19)

```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()  ```

```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  ```

### 2 个回答

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

X没有定义。

```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()```

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

```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))```

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