此 Python 3.11 脚本显示两个图形(轴):
import numpy as np, matplotlib.pyplot as plt
def onclick(event):
print(event.inaxes)
fig, axs = plt.subplots(ncols=2, nrows=1, figsize=(3.5, 2.5), layout="constrained")
axs[0].plot(np.random.rand(10))
axs[1].plot(np.random.rand(10))
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
首先单击左侧图表,然后单击右侧图表,会生成:
Axes(0.102541,0.111557;0.385554x0.871775)
Axes(0.602541,0.111557;0.385554x0.871775)
我看到第一个
Axes
属性根据我单击的图表而变化:0.102541
代表左侧,0.602541
代表右侧。该房产的名称是什么?有没有一种简单的方法来导出从 axs
单击的 event
的索引?
刚刚在 mpl-discord 上看到你的问题,我想我会看看:-)
这里有一些关于其工作原理的说明:
event.inaxes
为您提供触发事件的 Axes
对象left
, bottom
, width
xheight
) 相对图形坐标)如果您想获取
axs
列表中轴的索引,您可以这样做:
import numpy as np, matplotlib.pyplot as plt
fig, axs = plt.subplots(ncols=2, nrows=1, figsize=(3.5, 2.5), layout="constrained")
axs[0].plot(np.random.rand(10))
axs[1].plot(np.random.rand(10))
axs = axs.tolist() # convert to list so we can use .index(...) to find elements
def onclick(event):
if event.inaxes in axs:
print(axs.index(event.inaxes))
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
...并回答问题“此房产的名称是什么?”
就是左下角的位置!
axs[0].get_position().x0
>>> 0.10289777777777778
axs[1].get_position().x0
>>> 0.6028977777777779
axs
NumPy 数组来简化:
import numpy as np, matplotlib.pyplot as plt
def onclick(event):
if (i := np.argwhere(axs == event.inaxes)).size:
print(i[0, 0])
fig, axs = plt.subplots(ncols=2, nrows=1, figsize=(3.5, 2.5), layout="constrained")
axs[0].plot(np.random.rand(10))
axs[1].plot(np.random.rand(10))
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
def onclick(event):
if ax := event.inaxes:
print('axes: ', ax.figure.axes.index(ax), '\n',
'bounds:', ax._position.bounds)