python matplotlib 添加图例
时间: 2023-04-27 14:00:37 浏览: 118
要在 Python Matplotlib 中添加图例,可以使用 `legend()` 函数。该函数可以在图表中添加一个图例,用于解释图表中的不同元素。
例如,以下代码将在 Matplotlib 中创建一个简单的折线图,并添加一个图例:
```python
import matplotlib.pyplot as plt
# 创建数据
x = [1, 2, 3, 4, 5]
y1 = [1, 3, 2, 4, 5]
y2 = [2, 4, 3, 5, 6]
# 绘制折线图
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
# 添加图例
plt.legend()
# 显示图表
plt.show()
```
在上面的代码中,`plot()` 函数用于绘制两条折线,每条折线都有一个标签。`legend()` 函数用于添加图例,它会自动识别每个折线的标签,并将其显示在图例中。最后,`show()` 函数用于显示图表。
相关问题
python matplotlib添加图例
为了在Python的Matplotlib中添加图例,你可以使用plt.legend()函数。该函数可以接受不同的参数来自定义图例的位置、标签和样式。下面是一个示例代码:
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()
在这个例子中,我们使用了两个线条来绘制y = x^2和y = x^3的曲线,并使用label参数来设置每个线条的标签。然后,我们使用plt.legend()函数将图例添加到图表中,并通过设置loc参数来指定图例的位置。在这个例子中,我们将图例放在右上角。
pythonmatplotlib绘图图例
在Python中使用matplotlib绘图时,图例是非常重要的一部分,它可以帮助我们更好地理解图表中的数据。下面是两种常见的绘制图例的方法:
1.使用label参数和legend函数绘制图例
```python
import matplotlib.pyplot as plt
# 生成数据
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]
# 绘制折线图
plt.plot(x, y1, label='y1')
plt.plot(x, y2, label='y2')
# 添加图例
plt.legend()
# 显示图表
plt.show()
```
2.使用handles和labels参数绘制图例
```python
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
生成数据
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]
# 绘制折线图
line1 = Line2D(x, y1, color='blue', label='y1')
line2 = Line2D(x, y2, color='red', label='y2')
plt.gca().add_artist(line1)
plt.gca().add_artist(line2)
# 添加图例
plt.legend(handles=[line1, line2])
# 显示图表
plt.show()
```