jupyter notebook添加图例语句
时间: 2024-04-04 18:28:19 浏览: 18
在Jupyter Notebook中,你可以使用Matplotlib库来添加图例。以下是添加图例的几种常见方法:
1. 使用`plt.legend()`函数:在绘制图形时,可以通过给每个曲线添加`label`参数来标记曲线的名称,然后使用`plt.legend()`函数来显示图例。示例代码如下:
```python
import matplotlib.pyplot as plt
# 绘制曲线
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')
# 添加图例
plt.legend()
# 显示图形
plt.show()
```
2. 使用`ax.legend()`函数:如果你使用了`matplotlib`的面向对象接口,可以通过创建一个`Axes`对象,并使用`ax.legend()`函数来添加图例。示例代码如下:
```python
import matplotlib.pyplot as plt
# 创建一个Figure和Axes对象
fig, ax = plt.subplots()
# 绘制曲线
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]
ax.plot(x, y1, label='y = x^2')
ax.plot(x, y2, label='y = x^3')
# 添加图例
ax.legend()
# 显示图形
plt.show()
```
3. 自定义图例位置:你可以使用`loc`参数来指定图例的位置。常见的位置包括'upper left'、'upper right'、'lower left'、'lower right'等。示例代码如下:
```python
import matplotlib.pyplot as plt
# 绘制曲线
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')
# 添加图例并指定位置
plt.legend(loc='upper right')
# 显示图形
plt.show()
```