python - How to use "RectangleSelector " widget of Matplotlib in TKinter -


i working on project have plot data read sensor user must select part of data plot , extract it. using python3, tkinter gui , matplotlib plotting. thought "rectangleselector" widget of matplotlib suitable job. however, couldn't manage rectangleselector widget work eve though examine example provided matplotlib reference. can me this?

right when try run code get: "attributeerror: 'nonetype' object has no attribute 'mpl_connect'"

the code looks this:

import matplotlib matplotlib.use("tkagg") matplotlib.backends.backend_tkagg import figurecanvastkagg, navigationtoolbar2tkagg matplotlib.widgets import rectangleselector matplotlib.figure import figure  matplotlib import style style.use('ggplot')  import tkinter tk  import numpy np  #import analogread  large_font= ("verdana", 12) sample_max = 100000.0 # maximum sampling rate sample = 1000.0 # sampling rate sample_size = 2000 # self explaining length = sample_size*10  f = figure(figsize=(10,5), dpi=100)#plt.figure(figsize=(10,5), dpi=100)#    = f.add_subplot(111)  time = np.zeros(1) data = np.zeros(1)   def line_select_callback(eclick, erelease):     'eclick , erelease press , release events'     x1, y1 = eclick.xdata, eclick.ydata     x2, y2 = erelease.xdata, erelease.ydata     print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2))     print(" button used were: %s %s" % (eclick.button, erelease.button))   def toggle_selector(event):     print(' key pressed.')     if event.key in ['q', 'q'] , toggle_selector.rs.active:         print(' rectangleselector deactivated.')         toggle_selector.rs.set_active(false)     if event.key in ['a', 'a'] , not toggle_selector.rs.active:         print(' rectangleselector activated.')         toggle_selector.rs.set_active(true)  toggle_selector.rs = rectangleselector(a, line_select_callback,                                        drawtype='box',                                        button=[1, 3],  # don't use middle button                                        minspanx=5, minspany=5,                                        spancoords='pixels',                                        interactive=true)    class appgui(tk.tk):     def __init__(self, *args, **kwargs):          tk.tk.__init__(self, *args, **kwargs)          #tk.tk.iconbitmap(self, default="clienticon.ico")         tk.tk.wm_title(self, "autocorrelation")           container = tk.frame(self)         container.pack(side="top", fill="both", expand = true)         container.grid_rowconfigure(0, weight=1)         container.grid_columnconfigure(0, weight=1)          self.frames = {}         frame = mainframe(container, self)         self.frames[mainframe] = frame         frame.grid(row=0, column=0, sticky="nsew")         self.show_frame(mainframe)      def show_frame(self, cont):          frame = self.frames[cont]         frame.tkraise()  class mainframe(tk.frame):       def __init__(self, parent, controller):          global data, time, f, a, sample          tk.frame.__init__(self, parent)         label = tk.label(self, text="graph page!", font=large_font)         label.pack(pady=10,padx=10)           #(time, data) = analogread.read(sample, sample_size)           a.plot([1,5,8],[4,2,7])                  canvas = figurecanvastkagg(f, self)         canvas.show()         canvas.get_tk_widget().pack(side=tk.bottom, fill=tk.both, expand=true)          toolbar = navigationtoolbar2tkagg(canvas, self)         toolbar.update()         canvas._tkcanvas.pack(side=tk.top, fill=tk.both, expand=true)          canvas.mpl_connect('key_press_event', toggle_selector)          #self._update(sample, sample_size, length)      def _setrate(self,val):         global sample         sample = float(val)      def _setsize(self,val):         global sample_size         sample_size = int(val)     if __name__ == "__main__":     app = appgui()              app.mainloop() 

and full error report below:

traceback (most recent call last):    file "<ipython-input-340-63c18d2a9507>", line 1, in <module>     runfile('c:/users/autocorrelation/documents/autocorrelation/lol.py', wdir='c:/users/autocorrelation/documents/autocorrelation')    file "c:\users\autocorrelation\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile     execfile(filename, namespace)    file "c:\users\autocorrelation\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile     exec(compile(f.read(), filename, 'exec'), namespace)    file "c:/users/autocorrelation/documents/autocorrelation/lol.py", line 60, in <module>     interactive=true)    file "c:\users\autocorrelation\anaconda3\lib\site-packages\matplotlib\widgets.py", line 1744, in __init__     state_modifier_keys=state_modifier_keys)    file "c:\users\autocorrelation\anaconda3\lib\site-packages\matplotlib\widgets.py", line 1144, in __init__     self.connect_default_events()    file "c:\users\autocorrelation\anaconda3\lib\site-packages\matplotlib\widgets.py", line 1179, in connect_default_events     self.connect_event('motion_notify_event', self.onmove)    file "c:\users\autocorrelation\anaconda3\lib\site-packages\matplotlib\widgets.py", line 129, in connect_event     cid = self.canvas.mpl_connect(event, callback)  attributeerror: 'nonetype' object has no attribute 'mpl_connect'    

at point @ define rectangle selector, figure canvas not yet defined (none) , hence error 'nonetype' object has no attribute 'mpl_connect'.

you therfore need define rectangle selector after setting figure canvas. ensures axes provide rectangle selector resides in figure, has canvas set.

    canvas = figurecanvastkagg(f, self)     # ...     toggle_selector.rs = rectangleselector(a, line_select_callback, ..., interactive=true)     # ...     canvas.mpl_connect('key_press_event', toggle_selector) 

Comments

Popular posts from this blog

Add new key value to json node in java -

javascript - Highcharts Synchronized charts with missing data points -

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -