简体   繁体   中英

Matplotlib picker event on secondary y-axis

I want to enable picker event (clicking on a dot and its coordinates are printed), but on a plot with a secondary y-axis.

For example, this is adopted from the twinx example . The picker event is somehow only enabled on the second axis (sine line):

import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b.',picker=5)
ax1.set_xlabel('time (s)')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
s2 = np.sin(2 * np.pi * t)
ax2.plot(t, s2, 'r.',picker=5)
ax2.set_ylabel('sin', color='r')
ax2.tick_params('y', colors='r')


def onpick1(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    print('Point: ', zip(np.take(xdata, ind), np.take(ydata, ind)))
fig.canvas.mpl_connect('pick_event', onpick1)
fig.tight_layout()
plt.show()

您只需要更改 zorder:

ax.set_zorder(axTwin.get_zorder() + 1)

This is the standard behaviour of twinx . From the documentation :

For those who are 'picking' artists while using twinx, pick events are only called for the artists in the top-most axes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM