get Coordinates of matplotlib plot figure python with mouse click

Bil*_*rab 5 python tkinter matplotlib mouseevent coordinates

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()
Run Code Online (Sandbox Code Playgroud)

小智 1

获得准确的结果,ix并且iy浮点数达到您想要的精度。问题是格式

print 'x = %d, y = %d' % (ix, iy)
Run Code Online (Sandbox Code Playgroud)

%d意味着数字应该显示为整数,而这正是这里发生的。如果您尝试%f使用浮点表示:

print 'x = %f, y = %f' % (ix, iy)
Run Code Online (Sandbox Code Playgroud)

您会发现您得到了准确的结果。