python matplotlib设置图例
时间: 2023-12-19 13:32:36 浏览: 28
```python
import matplotlib.pyplot as plt
# 绘制图形
plt.plot([1, 2, 3, 4], label='Line 1')
plt.plot([4, 3, 2, 1], label='Line 2')
# 设置图例位置
plt.legend(loc='upper right')
# 显示图形
plt.show()
```
相关问题
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()
```
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参数来指定图例的位置。在这个例子中,我们将图例放在右上角。