我想制作一个可以覆盖图中所有子图的图例。如果我设置它的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
会更改不同艺术家的绘制顺序(例如,参见 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()
,它返回图中的所有艺术家,从而允许迭代所有艺术家
。
关于python - matplotlib:使图例出现在其他子图上方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36227027/