Python绘图中怎么使两个图例在两行
时间: 2024-11-20 20:41:06 浏览: 46
在`matplotlib`中,如果需要让两个图例在不同行显示,通常情况下图例默认会尽量紧凑排列。但是,通过一些自定义设置,我们可以达到分行的效果。这里有一个稍微复杂的方法,使用`subplots_adjust`调整子图之间的间距,以及`make_axes_locatable`来添加额外的空间来放置图例。
下面是一个示例代码,演示如何做到这一点:
```python
import matplotlib.pyplot as plt
import numpy as np
# 数据
data1 = [1, 2, 3, 4, 5]
data2 = [6, 7, 8, 9, 10]
# 创建子图
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(6, 8), gridspec_kw={'height_ratios': [3, 1]})
# 分别在每个轴上绘制折线
ax1.plot(data1, label='Line 1')
ax1.legend(title='Legend for Subplot 1', loc='upper center', bbox_to_anchor=(0.5, -0.15)) # 将图例放在底部中心
ax2.plot(data2, label='Line 2')
ax2.legend(loc='center right', bbox_to_anchor=(1.1, 0.5)) # 将图例放在右下角
# 调整子图之间的间距以便图例分开
fig.tight_layout(rect=[0, 0, 1, .95]) # 限制总高度
fig.subplots_adjust(hspace=.5)
plt.show()
```
在这个例子中,我们在每个子图上都设置了独立的图例,然后通过`tight_layout`和`subplots_adjust`来调整子图空间,使得第二个图例处在第二张子图的右侧,并且这两个图例不在同一行。
注意这里的`bbox_to_anchor`参数可以帮助你在指定位置摆放图例框,第一个值是水平方向上的相对距离,第二个值是垂直方向上的距离。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)