2024/6/4

所学时间:2小时

代码行数:100

博客园数:1篇

所学知识:

【题目描述】设
图片2.png

图片3.png

图片4.png
,其中
图片5.png
,完成下列操作:

(1)在同一坐标系下用不同的颜色和线型绘制y1、y2和y3三条曲线;

(2)在同一绘图框内以子图形式绘制y1、y2和y3三条曲线。

【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。

import numpy as np

import matplotlib.pyplot as plt

# 定义 x 的范围

x = np.linspace(0, 10, 100)

# 定义 y1、y2、y3 函数

y1 = x ** 2

y2 = np.cos(2 * x)

y3 = y1 * y2

# 绘制三条曲线在同一坐标系下

plt.figure(figsize=(10, 5))

plt.plot(x, y1, color='blue', linestyle='-', label='y1 = x^2')

plt.plot(x, y2, color='red', linestyle='--', label='y2 = cos(2x)')

plt.plot(x, y3, color='green', linestyle='-.', label='y3 = y1 * y2')

plt.xlabel('x')

plt.ylabel('y')

plt.title('Three Functions in the Same Coordinate System')

plt.legend()

plt.grid(True)

plt.show()

# 绘制三条曲线以子图形式显示

plt.figure(figsize=(10, 10))

# 子图1

plt.subplot(3, 1, 1)

plt.plot(x, y1, color='blue', linestyle='-')

plt.xlabel('x')

plt.ylabel('y1')

plt.title('y1 = x^2')

# 子图2

plt.subplot(3, 1, 2)

plt.plot(x, y2, color='red', linestyle='--')

plt.xlabel('x')

plt.ylabel('y2')

plt.title('y2 = cos(2x)')

# 子图3

plt.subplot(3, 1, 3)

plt.plot(x, y3, color='green', linestyle='-.')

plt.xlabel('x')

plt.ylabel('y3')

plt.title('y3 = y1 * y2')

plt.tight_layout() # 调整子图布局,使其更加美观

plt.show()

 

posted @ 2024-06-04 22:40  为20岁努力  阅读(1)  评论(0编辑  收藏  举报