matplotlib 两个传说出情节

matplotlib two legends out of plot

我在显示情节之外的两个图例时遇到了问题。 在 inside 图中显示多个图例很容易 - 它在 matplotlib 文档的示例中进行了描述。 即使在情节之外显示一个图例也很容易,因为我在 Whosebug 上发现了这里(例如 here)。 但我找不到工作示例来展示情节之外的两个传说。 适用于一个图例的方法在这种情况下不起作用。

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

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')

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

...
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 忽略了添加

的对象的大小和位置
plt.gca().add_artist(obj)

我该如何解决这个问题?

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

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

leg.get_frame().set_alpha(0)

这是结果(为了示例目的没有设置 alpha):

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

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')

我可以建议以下解决方案:

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

结果是