How to make matplotlib open a window for user comments?

I have an interactive plot that listens for certain keystrokes and clicks, but I want the user to be able to add a comment. I know that artist events usually do not allow this (they listen to individual clicks, but can I open matplotlib in a new window with a small “insert comment” area? Ideally, the window goes out and returns to the main (original) when the user clicks for refund.

import numpy as np import matplotlib.pyplot as plt def onpick(event): ''' ''' if event.mouseevent.button == 1: #only want lmb clicks selection = event.artist xdata = selection.get_xdata() ydata = selection.get_ydata() ind = event.ind point = tuple(zip(xdata[ind], ydata[ind])) xclick,yclick = point[0] print('[x,y]=',xclick,yclick) def on_key(event): ''' Handles predefined key-press events ''' print('Key press:\'%s\'' %(event.key)) if event.key == ' ': #spacebar print 'Space' #do a thing if event.key == 'e': print 'eeeeee' #do another thing if event.key == 'C': print 'How do make a comment. ...' comment = 'Whatever the user entered' return comment # when done return fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, facecolor='#FFFFCC') x, y = 4*(np.random.rand(2, 100) - .5) ax.plot(x, y, 'o', picker = 6) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) keyID = fig.canvas.mpl_connect('key_press_event', on_key) clickID = fig.canvas.mpl_connect('pick_event', onpick) plt.show() 
+1
source share
1 answer

Matplotlib will soon introduce a TextBox widget (possibly in version 2.1 (?)). See Its use in this example .

Until then, you can use Tkinter tkSimpleDialog to request a user comment.

 w = tkSimpleDialog.askstring("Title", "Please type comment") 

You can then annotate the last selected comment point.

Full example (which runs in python 2.7):

 import numpy as np import matplotlib.pyplot as plt import Tkinter, tkSimpleDialog xy = [(0,0)] def onpick(event): ''' ''' if event.mouseevent.button == 1: #only want lmb clicks selection = event.artist xdata = selection.get_xdata() ydata = selection.get_ydata() ind = event.ind point = tuple(zip(xdata[ind], ydata[ind])) xclick,yclick = point[0] xy[0] = (xclick,yclick) print('[x,y]=',xclick,yclick) def on_key(event): print('Key press:\'%s\'' %(event.key)) if event.key == 'c': root = Tkinter.Tk() root.withdraw() w = tkSimpleDialog.askstring("Title", "Please type comment") if w != None: ax.annotate(w, xy=xy[0], xytext=(20,-20), arrowprops=dict(facecolor='black', width=2, headwidth=6), textcoords='offset points') ax.figure.canvas.draw_idle() fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, facecolor='#FFFFCC') x, y = 4*(np.random.rand(2, 100) - .5) ax.plot(x, y, 'o', picker = 6) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) keyID = fig.canvas.mpl_connect('key_press_event', on_key) clickID = fig.canvas.mpl_connect('pick_event', onpick) plt.show() 

enter image description here

+1
source

Source: https://habr.com/ru/post/973621/


All Articles