python - Matplotlib:在注释上方渲染补丁

标签 python matplotlib

我有几个补丁(圆圈),里面标有文本作为注释。这两个圆圈是可拖动的,因此它们有可能重叠。问题是,所有 圆圈始终在所有 注释之前呈现,因此所有注释都呈现在圆圈上方。这意味着,如果圆 1 与圆 2 重叠,则两个圆的注释均可见。这看起来有点奇怪和错误。我尝试使用 zorder 参数来解决这个问题,但该参数没有效果。进一步研究文档后,这种行为似乎被硬编码到渲染器中,并且我还没有找到任何解决方案来改变这种行为。

这是我当前使用注释绘制单个圆圈的方法:

def draw_circle_with_annotation(ax, position, label, point_size):
    trans = ScaledTranslation(position[0], position[1], ax.transData)
    point = Circle((0, 0), point_size, transform=trans, picker=True)
    ax.add_patch(self.point)

    label = ax.annotate(label, xy=(0.5, 0.5), xycoords=point, fontsize=10, ha='center', va='center_baseline')

对每个圆连续调用此函数,以便交替执行面片和注释的绘制调用。所有注释仍然呈现在所有补丁之上。

但是,有没有办法在注释上方绘制补丁?

最佳答案

Matplotlib 首先绘制具有最低 zorder 的元素,然后将较高 zorder 绘制在顶部。当元素具有相同的 zorder 时,补丁会在文本之前绘制。解决方案是为每个注释赋予一个新的、更高的 zorder:

import matplotlib.pyplot as plt
from matplotlib.transforms import ScaledTranslation
from matplotlib.patches import Circle
import numpy as np

zorder = 2

def draw_circle_with_annotation(ax, position, label, point_size):
    global zorder
    point = Circle(position, point_size, picker=True, facecolor='tomato', edgecolor='k', zorder=zorder)
    ax.add_patch(point)
    ax.annotate(label, xy=position, fontsize=14, ha='center', va='center_baseline', zorder=zorder)
    zorder += 1

fig, ax = plt.subplots()
for i in range(10):
    draw_circle_with_annotation(ax, np.random.uniform(10, [50, 25], 2), f'label\n{i + 1}', 5)
ax.autoscale()
ax.set_aspect('equal')
plt.show()

example plot

关于python - Matplotlib:在注释上方渲染补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63310120/

相关文章:

python - list.pop() 和 list = list[ :-1] 的区别

python - 百分比列表切片

python - Turtle 参数化代码可以在 Python 3 中运行,但不能在 Python2 中运行

python - 为什么 Bokeh 教程使用显式导入而不是别名?

python - python中的单行(或列)热图

python - Seaborn matplotlib : Cannot get window extent w/o renderer (RuntimeError)

Python:Matplotlib Surface_plot

python - matplotlibrc.py 未重置后端

python - 如何在 Bokeh 图中旋转 X 轴标签?

python - 如何在matplotlib中设置条形图的大小