我面临着在情节之外显示两个图例的问题。
显示多个图例inside绘图很简单 - matplotlib 文档中通过示例对其进行了描述。
即使在情节之外显示一个图例也相当容易,正如我在 stackoverflow 上发现的那样(例如here https://stackoverflow.com/questions/10101700/moving-matplotlib-legend-outside-of-the-axis-makes-it-cutoff-by-the-figure-box)。
但我找不到工作示例来显示情节之外的两个图例。
在这种情况下,适用于一个图例的方法不起作用。
这是一个例子。
首先是基本代码:
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 尊重正常图例的位置和大小,将其移动到右下角并hide它与代码:
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')