5

I have been trying to get the mouse x,y coordinates to variables according to matplotlib plot scale not pixels but it only returns me the integer components like 0.0 or 1.0 I want to return the accurate number like 0.1245 here is my code

import matplotlib
import Tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt


def onclick(self,event):
    ix, iy = float(event.xdata), float(event.ydata)

    print 'x = %d, y = %d' % (
        ix, iy)



root = tk.Tk()
circle1 = plt.Circle((0, 0), 1, color='blue')

f = plt.figure()
a = f.add_subplot(111)
f, a = plt.subplots()
a.add_artist(circle1)
a.set_xlim(-1.1, +1.1)
a.set_ylim(-1.1, +1.1)

#a.plot(circle1)
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

canvas.mpl_connect('button_press_event', onclick)

canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

root.mainloop()
2
  • That's interesting. I'm trying this in Python 3, and apart from minor changes (Tkinter -> tkinter, string formatting and def onclick(self, event) -> def onclick(event)), it gives me perfectly accurate results. Commented Feb 24, 2017 at 9:33
  • actualy yes python 3 differs of python with some minor changes, thanks for reply :) Commented Feb 24, 2017 at 12:27

1 Answer 1

1

You are getting accurate results, ix and iy are floats with the accuracy you want. The problem is the formatting in

print 'x = %d, y = %d' % (ix, iy)

%d means that the number should be displayed as an integer, and exactly that is happening here. If you try out %f for float representation:

print 'x = %f, y = %f' % (ix, iy)

you'll see that you're getting accurate results.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.