3

I am a quite new user of matplotlib. When plotting a surface (3D) with matplotlib and plot_surface, a window appears with the graph. In that windows, on the bottom right corner there is the coordinates of the actual position of the mouse. Is is possible to gain access to these values?

I have search on internet but very few solutions are proposed. For a 2D plot, these values are accessible using a tkinter.canvas but in 3D, when using the same technique the event.xdata and event.ydata did not return the good position for the mouse.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Antoine
  • 41
  • 3

2 Answers2

8

With ax.format_coord(mouseevent.xdata,mouseevent.ydata) you get the x, y, z values in a string ('x=0.222, y=0.452, z=0.826') from which you can extract the values.

For example for y-coordinate:

def gety(x,y):
    s = ax.format_coord(x,y)
    out = ""
    for i in range(s.find('y')+2,s.find('z')-2):
        out = out+s[i]
    return float(out)
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Thilo
  • 81
  • 1
  • 3
0

I tried @Thilo's answer and received only a single float. Using Python 3.8 and Matplotlib version 3.2.1.

Modified his function to this

def getxyz(event):
    s = ax.format_coord(event.xdata, event.ydata)
    out = [float(x.split('=')[1].strip()) for x in s.split(',')]
    print(out)
    return out

Many thanks, because without that answer I would never knew something like format_coord exist.

zwep
  • 1,207
  • 12
  • 26