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

标签 python matplotlib plot

我想制作一个可以覆盖图中所有子图的图例。如果我设置它的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()

enter image description here

谢谢!

最佳答案

一般来说,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.

关于python - matplotlib:使图例出现在其他子图上方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36227027/

相关文章:

python - 如何在 Django Admin 中向用户显示数据库错误

python - 反射(reflect)对多个子图的事件处理

Python - Matplotlib,绘制常量场

python - Pandas DataFrame - 将一列的值与相同的索引合并到列表中

python - 在python中使用lambda表达式在循环内生成函数

python - 如何每隔 2 分钟运行 100 个 python 文件?

python - 仅当添加和减去相同的值时,使用 pyplot 绘制常量函数才有效。为什么?

image - 用于图像数据的 Matlab hist 函数

Python tkinter on matplotlib 如何更新?

r - 加权ggplot2警告: Ignoring unknown aesthetics: weight