Python mouse click event.xdata using twinx()

Viewed 267

I am using canvas.mpl_connect mouse click listener for my e.g. 100x100 contourf plot with xlim from 0 to 99. Doing so I get e.g [x,y]= 10,20 as desired. However I have to display a second x-axis with different coordinates (e.g. xlim from 0.01 to 1) but I dont want event.xdata to return the coordinates in the style of the second axis. Is there a possibility to do so?

2 Answers

You could use the transformations in matplotlib. You would want to convert from the data-coordinates in ax2 to display coordinates (which are universal between the two axes) and then into data coordinates for ax1. Helpfully, you can combine transformations.

For example:

import matplotlib.pyplot as plt
import numpy as np

fig, ax1 = plt.subplots(1)

# First axis, with x-values going from 0 to 100
x1 = np.linspace(0, 100, 101)
y1 = np.sin(2 * np.pi * x1 / max(x1))
ax1.plot(x1, y1, 'b.-')

# Second axis, x values going from 0 to 1
ax2 = ax1.twiny()
x2 = np.linspace(0, 1, 11)
y2 = np.cos(2 * np.pi * x2 / max(x2))
ax2.plot(x2, y2, 'r.-')

# Create a combined transform from ax2 data to ax1 data
combinedTransform = ax2.transData + ax1.transData.inverted()

def onclick(event):
    # event has x and y in data coordinates for ax2:
    pt_data2 = (event.xdata, event.ydata)

    # Convert them into data coordinates for ax1:
    pt_data1 = combinedTransform.transform(pt_data2)  
    
    # ...

cid = fig.canvas.mpl_connect('button_press_event', onclick)

It feels like there would be a nicer way (somehow tell the event listener which axis you want the xdata and ydata to be valid for, but I don't know it. Sorry)

thanks, I implemented something like this as well. The problem is that there is actually no direct linear transformation behind my data. I solved the issue by just calling the second axis in a function after I finished setting the marker or choosing points. It's not beautiful but should be fine for a Master's thesis!

Related