python - 如何重新定位matplotlib图例而不改变地块
问题描述
我有一个带有 6 个子图的图,其数据非常相似。我只想要一个图例,我想把它放在两个子图上重叠,但似乎 matplotlib 阻止了这一点。如果我将图例向上移动一点,它会改变子图的格式,使其不会与另一个图重叠。所以我的问题是:如何在不影响子图的总体构成的情况下替换图例/如何允许重叠?
我已经尝试过loc
,bbox_to_anchor
但都重新格式化了子图(即更改轴)使用的语法:ax[1,1].legend(["line1",..,"lineN"],loc=(0.5,0.5)
和相同但 loc 替换为 bbob_to_anchor
编辑:我刚刚找到了这个答案,但我认为它对我不起作用,因为我没有在 plot 调用中定义标签。我根据该答案尝试的是:
handles,labels = ax[1,1].get_legend_handles_labels()
fig.legend(handles, ["line0",..,"lineN"], loc=(0.5,0.5))
但这给了我一个空洞的传说。只是一个小广场
EDIT2:对我的确切情况进行更多说明:
f, ax = plt.subplots(3,2, figsize=(10,8), sharex=True, sharey=True)
x = np.linspace(0,100,100)
y = np.random.rand(100,3)
ax[0,0].plot(x,y)
ax[0,1].plot(x,y)
ax[1,0].plot(x,y)
ax[1,1].plot(x,y)
ax[2,0].plot(x,y)
ax[2,1].plot(x,y)
//One single legend for the three lines represented in y. It should overlap part of subplot 0,1 and 1,1
解决方案
你也可以试试这个:
f, (ax1, ax2, ax3) = plt.subplots(3, figsize=(10,8), sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('Title')
plt.legend([l1, l2, l3],["label 1", "label 2", "label 3"], loc='center left', bbox_to_anchor=(1, 3.2))
plt.show()
推荐阅读
- flutter - 如何使用 Future 返回的字符串
颤振中的方法? - php - 如何从本地存储中获取阵列图像到刀片文件
- android - 在谷歌地图中实现 UI 组件,如 imageviews、recyclerviews
安卓中的标签 - java - 使用 apache poi 的工作表级自定义属性
- laravel - 有条件地对记录的均匀分布进行排序
- python - Discord.py 检查频道是否在类别中
- sockets - 非阻塞套接字可以和epoll的电平触发模式一起使用吗?
- python - Django wagtail登录需要不起作用
- html - 使用 jquery 附加 li 标签
- mysql - 无法在 Ubuntu 中使用 Navicat 创建新连接