我正面临着在剧情之外显示两个传说的问题。 显示多个传说里面情节很简单 - 它在matplotlib文档中的例子中描述。 即使在剧情之外显示一个传说也相当容易,因为我在这里找到了stackoverflow(例如here)。 但我找不到工作的例子来显示剧情之外的两个传说。 使用一个图例的方法在这种情况下不起作用。matplotlib两个传说出来的阴谋
这里是一个例子。 首先基本代码:
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)
我怎样才能解决这个添加对象的大小和位置?
到目前为止,我发现了一个解决方案,但它很讨厌:
创建三个传说,两人对视additiontal(由add_artist加)和一个正常的传说。 至于matplotlib尊重位置和法线传说的大小,将其移动到右下角和隐藏与代码它:
leg.get_frame().set_alpha(0)
下面是结果(不设置例如目的阿尔法):
它的行为完全是我想要的,但正如你知道它的讨厌。 下面是最终的代码:
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')
这样做几乎完美。我只需要对传说位置和情节规模进行一些调整,但它完全符合我的需求。谢谢! –