繁体   English   中英

matplotlib:使图例出现在其他子图上方

[英]matplotlib: Make legend appear above other subplots

我想制作一个可以覆盖图中所有子图的图例。 如果我设置其framealpha=1.0那么它将覆盖其子图上的内容,但是我也需要它也位于其他子图中的数据之上。 请注意,我需要红线才能通过图例。 “高于”是指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()

在此处输入图片说明

谢谢!

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

OP提出的未将图例覆盖在所有子图上的问题来自于为图例设置zorder的事实,该zorderzorder axes[0] zorder图的子级。 因此,更改该值仅会影响axes[0]内的顺序。 使用函数get_zorder (例如axes[0].get_zorder() )可以检查zorder中不同的子图,并且可以看到zorder axes[0]zorder axes[1]具有相同的zorder 这将使图例不在右侧子图的前景上。

为了解决该问题,由于zorder axes[0]是带有图例的图, zorder应将其zorder设置为较高的值(例如, axes[0].set_zorder(100) )。 这样可以正确显示图例,如下图所示。 请注意,可以按不同的顺序绘制图中的艺术家。 figure一个有用功能是get_children() ,它返回图中的所有艺术家,从而允许对所有艺术家进行迭代。 带有图例的正确结果图像在前景上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM