如何在Python中使用def来绘制函数?(Matplotlib)
要在Python中使用def定义的函数绘制图形,可以遵循以下步骤 –
- 设置图形大小并调整子图之间和周围的填充。
- 使用 def 创建用户定义函数,即 f(x) 。
- 使用numpy创建 x 数据点。
- 使用 plot() 方法绘制 x 和 f(x) 。
- 使用 show() 方法显示图形。
例子
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def f(x):
return np.sin(x) + x + x * np.sin(x)
x = np.linspace(-10, 10, 100)
plt.plot(x, f(x), color='red')
plt.show()