Matplotlib 如何绘制使用def定义的函数
要在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()