matplotlib:使图例显示在其他子图上方

时间:2016-03-25 19:52:21

标签: python matplotlib plot

我想创建一个可以叠加图中所有子图的图例。如果我设置它的framealpha=1.0然后它覆盖了其子图上的内容,但是我需要它在"之上#34;其他子图中的数据也是如此。请注意,我需要让红线传递给传奇;通过以上'我在谈论z维度,而不是它的y位置。

以下是一个例子:

import matplotlib.pyplot as plt
import numpy as np

x1 = np.random.rand(25)
y1 = np.random.rand(25)
x2 = np.random.rand(25)
y2 = np.random.rand(25)

f, axes = plt.subplots(1,2)
axes[0].plot(x1,y1,'b-',label='data 1 blah blah blah this is a wide legend that should sit top of BOTH subplots')
axes[1].plot(x2,y2,'r-')
axes[0].axis('off')
axes[1].axis('off')

leg = axes[0].legend(bbox_to_anchor=(0.5, .8), loc=2, fontsize=8, frameon=True, framealpha = 1.0)
rect = leg.get_frame()
rect.set_facecolor([0.9,0.9,0.9])
leg.set_zorder(100)
plt.show()

enter image description here

谢谢!

1 个答案:

答案 0 :(得分:2)

通常,zorder会更改绘制不同艺术家的顺序(例如,请参阅demo中的相关matplotlib)。

OP提出的问题是没有将图例叠加在子图的所有之上,这是因为为图例设置了zorder这个事实是axes[0]中的子图。因此,更改该值只会影响axes[0]内的订单。使用函数get_zorder(例如,axes[0].get_zorder())可以检查zorder的不同子图,并且可以看到axes[0]axes[1]相同的zorder。这会导致图例不在右侧子图的前景中。

为了解决问题,由于axes[0]是带图例的情节,其zorder应设置为更高的值(例如axes[0].set_zorder(100))。 这样可以正确显示图例,如下图所示。 注意,以不同的顺序绘制图中的艺术家可以概括; figure的一个有用功能是get_children(),它返回图中的所有艺术家,从而允许迭代所有这些艺术家 。 Resulting image with legend correctly on the foreground.

相关问题