1

I want to use the cursor (x,y values get displayed at the bottom left of figure) to measure the y and x distance between two points, however this only works for the data plotted on the second axis.

Is there a way to switch back an forth between the second axis and first y-axis?

Please note: I do not want a programmatic way of getting distance between points, just to use the cursor when I am viewing data in the figure plot.

Not sure if this helps but my code is literally the example for plotting two axes from the matplotlib page:

    fig, ax1 = plt.subplots()
    ax1.plot(sensor1, 'b-')
    ax1.set_xlabel('(time)')
    # Make the y-axis label and tick labels match the line color.
    ax1.set_ylabel('Sensor 1', color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')


    ax2 = ax1.twinx()
    ax2.plot(sensor2, 'r.')
    ax2.set_ylabel('Sensor 2', color='r')
    for tl in ax2.get_yticklabels():
        tl.set_color('r')
    plt.show()
laserpython
  • 300
  • 1
  • 6
  • 21

1 Answers1

1

You can use the excellent answer here to get both coordinates displayed at the same time. In order to get distance between two points, you can then combine this idea with ginput to map from one to the other and add the result as a title,

import matplotlib.pyplot as plt
import numpy as np

#Provide other axis
def get_othercoords(x,y,current,other):

    display_coord = current.transData.transform((x,y))
    inv = other.transData.inverted()
    ax_coord = inv.transform(display_coord)
    return ax_coord

#Plot the data
fig, ax1 = plt.subplots()
t = np.linspace(0,2*np.pi,100)
ax1.plot(t, np.sin(t),'b-')
ax1.set_xlabel('(time)')
ax1.set_ylabel('Sensor 1', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')

ax2 = ax1.twinx()
ax2.plot(t,3.*np.cos(t),'r-')
ax2.set_ylabel('Sensor 2', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')

#Get user input
out = plt.ginput(2)

#2nd axis from input
x2b, x2t = out[0][0], out[1][0]
y2b, y2t = out[0][1], out[1][1]

#Draw line
ax2.plot([x2b, x2t],[y2b, y2t],'k-',lw=3)

#1st axis from transform
x1b, y1b = get_othercoords(x2b,y2b,ax2,ax1)
x1t, y1t = get_othercoords(x2t,y2t,ax2,ax1)
plt.title("Distance x1 = " + str(x1t-x1b) + " y1 = " + str(y1t-y1b) + "\n"
          "Distance x2 = " + str(x2t-x2b) + " y2 = " + str(y2t-y2b))
plt.draw()
plt.show()

which gives something like,

enter image description here

Community
  • 1
  • 1
Ed Smith
  • 12,716
  • 2
  • 43
  • 55