plt.legend()
时间: 2023-10-29 20:32:01 浏览: 146
This is a function in the matplotlib library in Python that adds a legend to a plot. It takes no arguments and simply adds a legend to the current axes based on the labels set for each plotted element.
Example usage:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, label='linear')
plt.legend()
plt.show()
This code will plot a line graph of the data in x and y with a label of 'linear' on the graph. The plt.legend() function is then called, which will add a legend to the plot with the label 'linear'. The graph is displayed using the plt.show() function.
相关问题
plt.legend
plt.legend是一个用于在Matplotlib中添加图例的函数。它可以在图表中的不同位置添加文本标签,以帮助读者更好地理解数据。在使用plt.plot函数绘制多个曲线时,可以将曲线标记为不同的名称,并使用plt.legend函数自动为它们创建图例。例如,以下代码将绘制两个曲线,并将它们标记为“数据1”和“数据2”,然后使用plt.legend函数将它们添加到图表中:
```
import matplotlib.pyplot as plt
# 生成数据
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
# 绘制曲线
plt.plot(x, y1, label='数据1')
plt.plot(x, y2, label='数据2')
# 添加图例
plt.legend()
# 显示图表
plt.show()
```
这将在图表中添加一个图例,显示“数据1”和“数据2”标签,并将它们与相应的曲线颜色匹配。
plt. legend
The legend in matplotlib is a box containing a label and a symbol or line for each plot element. It helps in identifying the different elements of the plot. The `plt.legend()` function is used to add the legend to the plot.
Syntax:
```python
plt.legend()
```
Parameters:
- `loc` (optional): specifies the location of the legend. The default value is `'best'`.
- `bbox_to_anchor` (optional): specifies the anchor point for the legend. The default value is `(1.0, 1.0)`.
- `title` (optional): specifies the title of the legend.
Example:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 4, 6, 8]
plt.plot(x, y1, label='y1')
plt.plot(x, y2, label='y2')
plt.legend()
plt.show()
```
Output:
![legend_example](https://user-images.githubusercontent.com/57391992/133863623-2aa0b1a7-5f5c-4a71-9f3c-9e8c566b2f42.png)
阅读全文