5.15
python函数图像绘制
• 所花时间:4
• 代码行数:415
• 博客容量:1
• 代码如下:
import numpy as np
import matplotlib.pyplot as plt
# 定义x的取值范围
x = np.linspace(0, 10, 400)
# 定义函数y1, y2, y3
y1 = x ** 2
y2 = np.cos(2 * x)
y3 = y1 * y2
# 绘制y1, y2和y3在同一坐标系下
plt.figure(figsize=(10, 6))
plt.plot(x, y1, label='y1 = x^2', color='blue', linestyle='-')
plt.plot(x, y2, label='y2 = cos(2x)', color='red', linestyle='--')
plt.plot(x, y3, label='y3 = y1 * y2', color='green', linestyle='-.')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot of y1, y2, and y3')
plt.legend()
plt.grid(True)
plt.show()
# 在同一绘图框内以子图形式绘制y1, y2和y3三条曲线
fig, axs = plt.subplots(3, 1, figsize=(10, 12))
# 子图1: y1
axs[0].plot(x, y1, label='y1 = x^2', color='blue')
axs[0].set_ylabel('y1')
axs[0].legend()
axs[0].grid(True)
# 子图2: y2
axs[1].plot(x, y2, label='y2 = cos(2x)', color='red')
axs[1].set_ylabel('y2')
axs[1].legend()
axs[1].grid(True)
# 子图3: y3
axs[2].plot(x, y3, label='y3 = y1 * y2', color='green')
axs[2].set_xlabel('x')
axs[2].set_ylabel('y3')
axs[2].legend()
axs[2].grid(True)
# 设置子图标题
fig.suptitle('Subplots of y1, y2, and y3')
plt.show()
浙公网安备 33010602011771号