如何在不更改图的情况下重新放置Matplotlib图例 [英] How to reposition matplotlib legend without plots to change

查看:47
本文介绍了如何在不更改图的情况下重新放置Matplotlib图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含6个子图的图,这些图的数据非常相似.我只想要一个图例,并且希望将其放置为与两个子图重叠,但是matplotlib似乎可以防止这种情况.如果我将图例稍微上移,它将更改子图的格式,使其不会与其他图重叠.所以我的问题是:如何在不影响子图的总体构成的情况下替换图例/如何允许重叠?

I have a plot with 6 subplots with very similar data. I only want one legend and I would like to place it such that it overlaps two subplots, but it seems matplotlib prevents this. If I move the legend a bit up it changes the format of the subplots such that it doesn't overlap another plot. So my question would be: how to replace the legend without affecting the general make up of the subplots/how to allow overlapping?

我已经尝试过使用 loc bbox_to_anchor ,但是都重新格式化了子图(即更改了轴)使用的语法: ax [1,1] .legend(["line1",..,"lineN"],loc =(0.5,0.5)和相同,但loc被bbob_to_anchor

I have tried both with loc and bbox_to_anchor but both reformat the subplots (i.e. changes axes) Used syntax: ax[1,1].legend(["line1",..,"lineN"],loc=(0.5,0.5) and the same but loc replaced with bbob_to_anchor

我刚刚找到了答案,但它对我不起作用,因为我没有在标签内部定义标签情节电话.根据该答案,我尝试的是:

I have just found this answer but it doesn't work for me I think because I'm not defining the labels inside the plot call. What I tried based on that answer was:

handles,labels = ax[1,1].get_legend_handles_labels()
    fig.legend(handles, ["line0",..,"lineN"], loc=(0.5,0.5))

但这给了我一个空洞的传说.只是一个小方块

But that gives me an empty legend. Just a little small square

我的具体情况需要更多澄清:

A bit more clarification to my exact situation:

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

推荐答案

好的,我是根据自己找到解决方案的答案,但略有不同.有效的是:

Oke I found the solution myself based on this answer but slightly different. What worked is:

handles = ax[0,0].get_lines()
labels = ["line0",...,"lineN"] #obviously expand this and do not use ...
fig.legend(handles, labels, loc=(0.5,0.5)

因此诀窍是,如果未在绘图调用中定义标签,则使用 get_lines 而不是 get_legend_handles_labels .

So the trick is to use get_lines instead of get_legend_handles_labels if you haven't define labels in your plot calls.

这篇关于如何在不更改图的情况下重新放置Matplotlib图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆