1.创建四个子图,第一个子图绘制y=x的图像;第二个子图绘制y=x2的图
像;第三个子图绘制y=sin(x)的图像;第四个子图绘制y=logx的图像。
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
x = np.linspace(-10, 10, 100)
y1 = x
axes[0, 0].plot(x, y1)
axes[0, 0].set_title("y = x")
y2 = x*x
axes[0, 1].plot(x, y2)
axes[0, 1].set_title("y = x2")
y3 = np.sin(x)
axes[1, 0].plot(x, y3)
axes[1, 0].set_title("y = sin(x)")
x_positive = x[x > 0] # 限定 x > 0,避免 log(0) 的错误
y4 = np.log(x_positive)
axes[1, 1].plot(x_positive, y4)
axes[1, 1].set_title("y = log(x)")
plt.tight_layout()
plt.show()