get Coordinates of matplotlib plot figure python with mouse click

£可爱£侵袭症+ 提交于 2021-02-05 05:49:26

问题


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()

回答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.



来源:https://stackoverflow.com/questions/42424626/get-coordinates-of-matplotlib-plot-figure-python-with-mouse-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!