matplotlib剧情中的两个传说 [英] matplotlib two legends out of plot

查看:95
本文介绍了matplotlib剧情中的两个传说的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临在剧情之外显示两个图例的问题. 在内部图中显示多个图例很容易-在matplotlib文档的示例中对此进行了描述. 正如我在stackoverflow上发现的那样,即使在情节之外显示一个图例也相当容易(例如

I'm facing problem with showing two legends outside of plot. Showing multiple legends inside plot is easy - its described in matplotlib doc's with examples. Even showing one legend outside of plot is rather easy as i found here on stackoverflow (ex. here). But i cant find working example to show two legends outside of the plot. Methods which work with one legend is not working in this case.

这里是一个例子. 首先是基本代码:

Here is an example. First of all base code:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.lines import Line2D
from matplotlib.font_manager import FontProperties

fig1 = plt.figure(figsize=(17,5))
fontP = FontProperties()
fontP.set_size('small')
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.grid()


# stuff for legend
rec1 = patches.Rectangle(
    (0.9, 0.25),   # (x,y)
    0.1,          # width
    0.1,          # height
    label='rectangle',
    **{
        'color': 'blue'
    }

)
ax1.add_patch(rec1)

leg = plt.legend(handles=[rec1], bbox_to_anchor=(0.7, -0.1))
fig1.savefig('sample1.png', dpi=90, bbox_inches='tight')

但是现在我想在情节的右侧绘制另一个图例. 这是代码:

But now i want to draw another legend at the right side of plot. Here is the code:

...
ax1.add_patch(rec1)

l1 = plt.legend(prop=fontP, handles=[rec1], loc='center left',
                box to_anchor=(1.0, 0.5))
plt.gca().add_artist(l1)

...

结果:

如您所见,第二个图例被截断了. 我的结论是matplotlib忽略了添加了

As you can see, second legend is truncated. My conclusion is that matplotlib ignores size and position of objects added with

plt.gca().add_artist(obj)

我该如何解决?

到目前为止,我找到了一个解决方案,但是非常讨厌:

So far i found a solution but its very nasty:

创建三个图例,其中两个作为附加图例(由add_artist添加),一个作为普通图例. 只要matplotlib尊重普通图例的位置和大小,请将其移至右下角并使用代码 hide 隐藏它:

Create three legends, two of them as additiontal (added by add_artist) and one as normal legend. As far matplotlib respect position and size of normal legends, move it to the right down corner and hide it with code:

leg.get_frame().set_alpha(0)

以下是结果(例如,未设置alpha):

Here are the results (without setting alpha for example purpose):

它的行为完全符合我的要求,但是您知道它很讨厌. 这是最终代码:

It behave exactly how i want it to but as you know its nasty. Here is the final code:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.lines import Line2D
from matplotlib.font_manager import FontProperties

fig1 = plt.figure(figsize=(17,5))
fontP = FontProperties()
fontP.set_size('small')
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.grid()

# stuff for additional legends
rec1 = patches.Rectangle(
    (0.9, 0.25),   # (x,y)
    0.1,          # width
    0.1,          # height
    label='rectangle',
    **{
        'color': 'blue'
    }
)
ax1.add_patch(rec1)

# example additional legends
l1 = plt.legend(prop=fontP, handles=[rec1], loc='center left',
bbox_to_anchor=(1.0, 0.5))
l2 = plt.legend(prop=fontP, handles=[rec1], loc=3, bbox_to_anchor=(0.4,
-0.2))

# add legends
plt.gca().add_artist(l1)
plt.gca().add_artist(l2)

# add third legend
leg = plt.legend(handles=[], bbox_to_anchor=(1.3, -0.3))
leg.get_frame().set_alpha(0) # hide legend

fig1.savefig('sample3.png', dpi=90, bbox_inches='tight')

推荐答案

我可以提出以下解决方案:

I can suggest the following solution:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()
fig.set_size_inches((10,10))

gs1 = gridspec.GridSpec(1, 1)
ax1 = fig.add_subplot(gs1[0])

x = np.arange(0.0, 3.0, 0.02)
y1 = np.sin(2*np.pi*x)
y2 = np.exp(-x)
l1, l2 = ax1.plot(x, y1, 'rs-', x, y2, 'go')

y3 = np.sin(4*np.pi*x)
y4 = np.exp(-2*x)
l3, l4 = ax1.plot(x, y3, 'yd-', x, y4, 'k^')

fig.legend((l1, l2), ('Line 1', 'Line 2'), "right")
fig.legend((l3, l4), ('Line 3', 'Line 4'), "lower center")

gs1.tight_layout(fig, rect=[0, 0.1, 0.8, 0.5])

我使用了来自matplotlib网站的示例,并遵循了有关紧密布局的文档 http://matplotlib.org/users/tight_layout_guide.html .

I used an example from matplotlib site and followed the documentation about tight layout http://matplotlib.org/users/tight_layout_guide.html.

结果为

这篇关于matplotlib剧情中的两个传说的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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