一张图出现两个legend如何实现
时间: 2024-05-16 11:13:02 浏览: 5
你可以使用 `matplotlib` 库中的 `ax.legend()` 方法,给每个 legend 对象指定一个 label。例如:
``` python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# 绘制第一个 legend
ax.plot([1, 2, 3], [4, 5, 6], label='Legend 1')
# 绘制第二个 legend
ax.plot([1, 2, 3], [7, 8, 9], label='Legend 2')
# 添加 legend
ax.legend(loc='upper left')
plt.show()
```
运行代码后,你将看到一个包含两个 legend 的图表。其中,第一个 legend 对象标记了第一条线,第二个 legend 对象标记了第二条线,它们分别位于图表的左上角。你也可以将它们放置在其他位置,例如右下角,只需要指定 `loc` 参数即可,例如 `ax.legend(loc='lower right')`。
相关问题
一张图出现两个legend四条线如何实现
您可以使用 Matplotlib 库来绘制这样的图形。下面是一个示例代码:
```python
import matplotlib.pyplot as plt
# 生成数据
x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [1, 4, 9, 16, 25]
y3 = [1, 3, 5, 7, 9]
y4 = [2, 4, 6, 8, 10]
# 绘制图形
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Line 1')
line2, = ax.plot(x, y2, label='Line 2')
line3, = ax.plot(x, y3, label='Line 3')
line4, = ax.plot(x, y4, label='Line 4')
# 添加 legend
ax.legend(handles=[line1, line2], labels=['Legend 1', 'Legend 2'])
ax.legend(handles=[line3, line4], labels=['Legend 3', 'Legend 4'])
plt.show()
```
这段代码会生成一张包含四条线和两个 legend 的图形。您可以根据需要修改代码中的数据和 legend 的标签。
python将两个折线图画在一张图上
可以使用 Matplotlib 库来实现这个功能。以下是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
# 生成数据
x = [1, 2, 3, 4, 5]
y1 = [10, 8, 6, 4, 2]
y2 = [2, 4, 6, 8, 10]
# 绘制折线图
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
# 添加图例和标签
plt.legend()
plt.xlabel('X Label')
plt.ylabel('Y Label')
# 显示图形
plt.show()
```
这段代码将会生成一个包含两条折线图的图形,其中 `x` 是横坐标,`y1` 和 `y2` 是两条折线图的纵坐标。使用 `plt.plot` 函数来绘制折线图,`label` 参数用于设置图例标签。最后使用 `plt.legend` 函数来添加图例,使用 `plt.xlabel` 和 `plt.ylabel` 函数来添加坐标轴标签,最后使用 `plt.show` 函数来显示图形。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)