在jupyter使用matplotlib分别绘制y=x 和y=x*x两个图像的代码
时间: 2024-09-09 15:13:08 浏览: 62
在Jupyter Notebook中使用Matplotlib绘制`y = x`和`y = x^2`两个图像非常简单,你可以按照下面的步骤操作:
首先,你需要导入所需的库:
```python
import matplotlib.pyplot as plt
```
然后,创建一个函数来生成数据:
```python
def plot_functions(x):
# y = x
linear_y = x
# y = x^2
quadratic_y = x**2
return linear_y, quadratic_y
```
接下来,在一个代码块中绘制两条线:
```python
# 创建x值范围
x_values = range(-10, 11)
# 获取每个函数对应的y值
linear_y, quadratic_y = plot_functions(x_values)
# 创建一个新的图形
plt.figure()
# 绘制两条线,分别对应直线和二次函数
plt.plot(x_values, linear_y, label='y = x')
plt.plot(x_values, quadratic_y, label='y = x^2', linestyle='--') # 使用虚线表示二次函数
# 添加图例、标签和标题
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Linear vs Quadratic Function')
# 显示图形
plt.show()
```
以上代码会创建一个显示`y = x`和`y = x^2`图像的窗口,并将它们放在同一个坐标系里。
阅读全文
相关推荐


















