如何防止matplotlib注释被其他轴裁剪

Jos*_*lis 5 python matplotlib

我在matplotlib中有一个带有多个子图(轴)的图,我想要注释轴内的点.然而,后续轴覆盖来自先前轴的注释(例如,子图(4,4,1)上的注释在子图(4,4,2)下).我已经设置了注释zorder漂亮和高,但无济于事:/

我已经使用了Joe Kington的改进版本令人敬畏的DataCursor来进行注释.

任何帮助将不胜感激

这是一个例子: 在此输入图像描述

Joe*_*ton 7

一种方法是弹出由annotate轴外创建的文本并将其添加到图中.这样它将显示在所有子图的顶部.

作为您遇到的问题的一个简单示例:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=5, ncols=5)
plt.setp(axes.flat, xticks=[], yticks=[], zorder=0)

ax = axes[0,0]
ax.annotate('Testing this out and seeing what happens', xy=(0.5, 0.5), 
            xytext=(1.1, .5), textcoords='axes fraction', zorder=100)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果我们只是将文本对象从轴中弹出并将其添加到图中,它将位于顶部:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=5, ncols=5)
plt.setp(axes.flat, xticks=[], yticks=[], zorder=0)

ax = axes[0,0]
ax.annotate('Testing this out and seeing what happens', xy=(0.5, 0.5), 
            xytext=(1.1, .5), textcoords='axes fraction', zorder=100)

fig.texts.append(ax.texts.pop())

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

你提到了DataCursor代码片段,你想要改变annotate方法:

def annotate(self, ax):
    """Draws and hides the annotation box for the given axis "ax"."""
    annotation = ax.annotate(self.template, xy=(0, 0), ha='right',
            xytext=self.offsets, textcoords='offset points', va='bottom',
            bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
            )
    # Put the annotation in the figure instead of the axes so that it will be on
    # top of other subplots.
    ax.figure.texts.append(ax.texts.pop())

    annotation.set_visible(False)
    return annotation
Run Code Online (Sandbox Code Playgroud)

我没有测试最后一点,但它应该工作......