# 如何使 Axes 对事件透明？

``````import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.set_gid("ax1")
ax2.set_gid("ax2")
fig.show()

def on_movement(event):
"""Write on the figure in which `Axes`object the event happened."""

width, height = fig.bbox.bounds[2:]
x = event.x/width
y = event.y/height
text = ax.get_gid() if (ax := event.inaxes) is not None else "None"
fig.texts[:] = []
fig.text(x, y, s=text, transform=fig.transFigure, c="white", bbox=dict(fc="#0055AA", ec="black"))
fig.canvas.draw()

fig.canvas.mpl_connect("motion_notify_event", on_movement)
``````

``````ax1.set_position((1/3, 1/3, 2/3, 2/3))
``````

``````ax2.set_visible(False)
``````

• 理想情况下，找到一个类似的设置，`zorder`以便“最高”轴获得事件。
• 丑陋的解决方法：将不可见轴的位置设置为`((0, 0, 1e-10, 1e-10))`
• 不那么难看：使用图形坐标将`event.x`,转换`event.y``event.xdata``event.ydata`因为我知道唯一可见的斧头。基本上`xdata1, ydata1 = ax1.transAxes.inverted().transform((event.x, event.y))`if`event.inaxes`不是 None + 看看是否有边缘情况。

Python 3.8.5
Matplotlib 3.1.3

``````ax1.set_zorder(2)
ax2.set_zorder(1)
...

def on_movement(event):
...
fig.text(x, y, ..., zorder=1000)
...
``````

0 条评论