def draw_tree(canvas, figure, loc = (0,0)): """Draws the tree figure onto the tree canvas.""" figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) # Position: convert from top-left anchor to center anchor canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) # Return a handle which contains a reference to the photo object # which must be kept live or else the picture disappears return photo
def draw_figure(canvas, figure, loc=(0, 0)): """ Draw a matplotlib figure onto a Tk canvas loc: location of top-left corner of figure on canvas in pixels. Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py """ figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) # Position: convert from top-left anchor to center anchor canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) # Return a handle which contains a reference to the photo object # which must be kept live or else the picture disappears return photo
def draw_figure(canvas, figure, loc=(0, 0)): """ draws a figure on the canvas with position relative to top left corner of canvas """ # relate figure_canvas = FigureCanvasAgg(figure) figure_canvas.draw() # get dimensions _, _, f_w, f_h = figure.bbox.bounds f_w, f_h = int(f_w), int(f_h) # create photo photo = tk.PhotoImage(master=canvas, width=f_w, height=f_h) # slap onto canvas canvas.create_image(loc[0] + f_w / 2, loc[1] + f_h / 2, image=photo) tkagg.blit(photo, figure_canvas.get_renderer()._renderer, colormode=2) # keep photo object alive or else it will disappear return photo
def draw_glycan_in_canvas(self, canvas, tree, root, names, h=100., w=100.): """ Draws a glycan on to a canvas Parameters: canvas: tk.Canvas where the image should be drawn tree: tree representation of the glycan root: id of root node in tree names: dictionary with node id as keys and resname as values h: height of figure in px w: width of figure in px Returns: glycan_image: image instance. This should be saved otherwise the image will be destroyed, thus not displayed. """ fig = mpl.figure.Figure(figsize=(h / self.dpi, w / self.dpi)) ax = fig.add_subplot(111) self.myDrawer.draw_tree(tree, root, names, root_pos=[0, 0], direction=1, ax=ax, axis=0) ax.axis('equal') ax.axis('off') ax.set_ylim((-1, 6)) ax.set_xlim((-3, 3)) # Add to tk window figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) glycan_image = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(figure_w / 2, figure_h / 2, image=glycan_image) tkagg.blit(glycan_image, figure_canvas_agg.get_renderer()._renderer, colormode=2) return glycan_image
def draw_figure(self): figure_canvas_agg = FigureCanvasAgg(self.fig) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = self.fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=self.canvas, width=figure_w, height=figure_h) # Position: convert from top-left anchor to center anchor self.canvas.create_image(self.fig_x + figure_w / 2, self.fig_y + figure_h / 2, image=photo) # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) # Return a handle which contains a reference to the photo object # which must be kept live or else the picture disappears return photo
def plot(): import matplotlib as mpl import matplotlib.backends.tkagg as tkagg from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) import pandas as pd fig = mpl.figure.Figure(figsize=(3, 2)) ax = fig.add_subplot(111) figure_canvas_agg = FigureCanvasAgg(fig) series = pandas.Series(data) dplt = series.plot(ax=ax) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) global the_fig_photo the_fig_photo = tk.PhotoImage(master=the_canvas, width=figure_w, height=figure_h) # Position: convert from top-left anchor to center anchor loc = (0, 0) the_canvas.delete("all") the_canvas.create_image(loc[0] + figure_w / 2, loc[1] + figure_h / 2, image=the_fig_photo) tkagg.blit(the_fig_photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) return the_fig_photo # XXX: has to be held
def display_matplotlib_figure_on_tk_canvas(self): # Draw a matplotlib figure in a Tk canvas self.matplotlib_2d_ax.clear() X = np.linspace(0, 2 * np.pi, 100) # Y = np.sin(X) Y = np.sin(X * np.int((np.random.rand() + .1) * 10)) self.matplotlib_2d_ax.plot(X, Y) self.matplotlib_2d_ax.set_xlim([0, 2 * np.pi]) self.matplotlib_2d_ax.set_ylim([-1, 1]) self.matplotlib_2d_ax.grid(True, which='both') self.matplotlib_2d_ax.axhline(y=0, color='k') self.matplotlib_2d_ax.axvline(x=0, color='k') # plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0) # Place the matplotlib figure on canvas and display it self.matplotlib_2d_figure_canvas_agg = FigureCanvasAgg( self.matplotlib_2d_fig) self.matplotlib_2d_figure_canvas_agg.draw() self.matplotlib_2d_figure_x, self.matplotlib_2d_figure_y, self.matplotlib_2d_figure_w, \ self.matplotlib_2d_figure_h = self.matplotlib_2d_fig.bbox.bounds self.matplotlib_2d_figure_w, self.matplotlib_2d_figure_h = int( self.matplotlib_2d_figure_w), int(self.matplotlib_2d_figure_h) self.photo = tk.PhotoImage(master=self.canvas, width=self.matplotlib_2d_figure_w, height=self.matplotlib_2d_figure_h) # Position: convert from top-left anchor to center anchor self.canvas.create_image( self.matplotlib_2d_fig_loc[0] + self.matplotlib_2d_figure_w / 2, self.matplotlib_2d_fig_loc[1] + self.matplotlib_2d_figure_h / 2, image=self.photo) tkagg.blit( self.photo, self.matplotlib_2d_figure_canvas_agg.get_renderer()._renderer, colormode=2) self.matplotlib_2d_fig_w, self.matplotlib_2d_fig_h = self.photo.width( ), self.photo.height() self.canvas.create_text(0, 0, text="Sin Wave", anchor="nw")
def draw_figure(self,data=[1/10,1/10,1/10,1/10,1/10,1/10,1/10,1/10,1/10,1/10], loc=(0, 0)): # determining pred max = 0 pred_num = 0 for index,val in enumerate(data): if(val>max): max = val pred_num = index self.predLabel.configure(text="PREDICTION: {} ".format(pred_num)) # plotting canvas = self.graph figure = mpl.figure.Figure(figsize=(4.2, 1.8)) figure_canvas_agg = FigureCanvasAgg(figure) ax = figure.add_subplot(111) figure.subplots_adjust(left=0.1, bottom=0.3, right=None, top=None, wspace=None, hspace=None) ax.set_ylim(bottom=0,top=1) figure.suptitle('prediction category') ax.get_xaxis().set_visible(True) ax.get_yaxis().set_visible(True) ax.get_yaxis().set_ticks([]) ax.get_xaxis().set_ticks([0,1,2,3,4,5,6,7,8,9]) index = np.arange(10) rects1 = ax.bar(index,data,color='red',label='certainty') ax.set_xlabel('Category') ax.set_ylabel('Certainty') figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w-10, height=figure_h-10) # Position: convert from top-left anchor to center anchor canvas.create_image(loc[0] + (figure_w / 2), loc[1] + (figure_h / 2), image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) # Return a handle which contains a reference to the photo object # which must be kept live or else the picture disappears self.figureHandle = photo return photo
def loadImage(self): # load image imagePath = self.imageList[self.cur] self.img = Image.open(imagePath) self.img = self.img.resize([int(self.zoom * s) for s in self.img.size]) self.mainPanel.config(width=900, height=600) self.progLabel.config(text="%04d/%04d" % (self.cur, self.total-1)) # initialise the drawing context with the image object as background self.draw = ImageDraw.Draw(self.img) # create font object with the font file and specify desired size font = ImageFont.truetype("arial.ttf", 20) # show current label if (self.df_labels[self.currentLabel].isnull()[self.cur]): self.currentLabelIndex = 0 else: self.currentLabelIndex = eye_open_levels.index(self.df_labels[self.currentLabel][self.cur]) self.currentLabelValue.config(text="%.2f (%s)" % (self.df_labels[self.currentLabel][self.cur],self.levelToPercentage(self.df_labels[self.currentLabel][self.cur]))) # print labels i = 0 for user in self.users_list: if (self.currentUser == user): if (self.currentEye == 'right'): color_text_r = c_lime color_text_l = c_red else: color_text_r = c_red color_text_l = c_lime else: color_text_r = c_red color_text_l = c_red # draw the message on the background self.draw.text(text_pos_r[i], "R_"+user+"_label: {:.2f}".format(self.df_labels[user+'_right'][self.cur]), fill=color_text_r, font=font) self.draw.text(text_pos_l[i], "L_"+user+"_label: {:.2f}".format(self.df_labels[user+'_left'][self.cur]), fill=color_text_l, font=font) i = i + 1 self.tkImg = ImageTk.PhotoImage(self.img) self.mainPanel.create_image(0, 0, image=self.tkImg, anchor=NW) #### print graphs matplotlib.pyplot.close('all') # close all figs before creating new one self.figure = plt.figure(figsize=(4.5,9),dpi=70) # create column fo frame number and append it to data frame df_frame_number = self.df_labels['frame_name'].str[-4:].astype(int) df_frame_elapsed_time = df_frame_number.apply(lambda x: round(float(x/self.video_fps),self.precision_digits)) self.df_labels['frame_number'] = df_frame_number self.df_labels['elapsed_time'] = df_frame_elapsed_time # plot graph for right eye ax_right = plt.subplot(1,2,1) # plot users labels i = 0 for user_eye in self.df_labels.columns: if (any(substring in user_eye for substring in self.users_list) and any(substring in user_eye for substring in ['right'])): if (user_eye == self.currentLabel): self.df_labels.plot(kind='line',style=line_styles[i%len(line_styles)],x=user_eye,y='frame_number', color=tuple(np.divide(c_lime,255)),ax=ax_right,label=user_eye) plt.scatter(self.df_labels[self.currentLabel][self.cur], self.cur, c=tuple(np.divide(c_blue,255))) else: self.df_labels.plot(kind='line',style=line_styles[i%len(line_styles)],x=user_eye,y='frame_number', color=tuple(np.divide(c_red,255)),ax=ax_right,label=user_eye) i = i + 1 # edit titles and axis plt.title(self.currentMedia+': labels vs frame_number',loc='left') plt.xlabel("labels_right") plt.ylabel('frame_number') ax_right.set_xlim([min(eye_open_levels[1:]),max(eye_open_levels[1:])]) ax_right.set_ylim([df_frame_number.iloc[0],df_frame_number.iloc[-1]]) ax_right.legend(loc='upper left') # plot graph for left eye ax_left = plt.subplot(1,2,2) # plot features i = 0 for user_eye in self.df_labels.columns: if (any(substring in user_eye for substring in self.users_list) and any(substring in user_eye for substring in ['left'])): if (user_eye == self.currentLabel): self.df_labels.plot(kind='line',style=line_styles[i%len(line_styles)],x=user_eye,y='frame_number', color=tuple(np.divide(c_lime,255)),ax=ax_left,label=user_eye) plt.scatter(self.df_labels[self.currentLabel][self.cur], self.cur, c=tuple(np.divide(c_blue,255))) else: self.df_labels.plot(kind='line',style=line_styles[i%len(line_styles)],x=user_eye,y='frame_number', color=tuple(np.divide(c_red,255)),ax=ax_left,label=user_eye) i = i + 1 # edit titles and axis plt.xlabel('labels_left') ax_left.set_xlim([min(eye_open_levels[1:]),max(eye_open_levels[1:])]) ax_left.set_ylim([df_frame_number.iloc[0],df_frame_number.iloc[-1]]) ax_left.legend(loc='upper left') ax_left.get_yaxis().set_visible(False) # set second y-axis (elapsed_time) ay2 = ax_left.twinx() # set the ticklabel position in the second x-axis, then convert them to the position in the first x-axis ay2_ticks_num = 6 newlabel = [round((y*df_frame_elapsed_time.iloc[-1]/(ay2_ticks_num-1)),self.precision_digits) for y in range(0, ay2_ticks_num)] newpos = [int(np.ceil(y*self.video_fps)) for y in newlabel] # set the second y-axis ay2.set_yticks(newpos) ay2.set_yticklabels(newlabel) ay2.yaxis.set_ticks_position('right') ay2.yaxis.set_label_position('right') ay2.spines['right'].set_position(('outward', 0)) ay2.set_ylabel('elapsed_time [Sec]') plt.gcf().subplots_adjust(right=0.87) # load image self.plotCurrEyePanel.config(width=360, height=550) figure_canvas_agg = FigureCanvasAgg(self.figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = self.figure.bbox.bounds figure_w, figure_h = int(figure_w+100), int(figure_h+100) self.figurePhoto = tk.PhotoImage(master=self.plotCurrEyePanel, width=figure_w, height=figure_h) self.plotCurrEyePanel.create_image(figure_w/2 + 25,figure_h/2 - 50,image=self.figurePhoto) tkagg.blit(self.figurePhoto, figure_canvas_agg.get_renderer()._renderer, colormode=2)
def main(): canvas_elem = sg.Canvas(size=(640, 480)) # get the canvas we'll be drawing on # define the form layout layout = [[ sg.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20') ], [canvas_elem], [ sg.ReadFormButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14') ]] # create the form and show it without the plot form = sg.FlexForm( 'Demo Application - Embedding Matplotlib In PySimpleGUI') form.Layout(layout) form.Finalize() canvas = canvas_elem.TKCanvas while True: button, values = form.ReadNonBlocking() if button is 'Exit' or values is None: exit(69) def PyplotScatterWithLegend(): import matplotlib.pyplot as plt from numpy.random import rand fig, ax = plt.subplots() for color in ['red', 'green', 'blue']: n = 750 x, y = rand(2, n) scale = 200.0 * rand(n) ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.3, edgecolors='none') ax.legend() ax.grid(True) return fig fig = PyplotScatterWithLegend() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(640 / 2, 480 / 2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
window.Finalize( ) # needed to access the canvas element prior to reading the window canvas_elem = window['canvas'] graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas) canvas = canvas_elem.TKCanvas dpts = [randint(0, 10) for x in range(10000)] # Our event loop for i in range(len(dpts)): event, values = window.read(timeout=20) if event == 'Exit' or event is None: exit(69) ax.cla() ax.grid() ax.plot(range(20), dpts[i:i + 20], color='purple') graph.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(640 / 2, 480 / 2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
def display_db(self, master, glycans, glycan_images, glycan_canvas): """Generates thumbnail images for all glycans in a database Parameters: master: master Canvas for drawing glycans: dictionary of glycans. Names as keys and connectivity topology as values glycan_images: list for storing generated images glycan_canvas: list for storing generated canvas glycan_ttp: list for storing labels for each glycan """ i = 0 j = 0 counter = 0 for name in glycans.keys(): # put five images per row if j and not j % 5: i += 1 j = 0 units = glycans[name]['UNIT'] root, tree, names = self.build_glycan_tree(units) fig = mpl.figure.Figure(figsize=(70. / self.dpi, 70. / self.dpi)) ax = fig.add_subplot(111) self.myDrawer.draw_tree(tree, root, names, root_pos=[0, 0], direction=1, ax=ax, axis=0) ax.axis('equal') ax.axis('off') ax.set_ylim((-1, 6)) ax.set_xlim((-3, 3)) # Add to tk window figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) canvas = tk.Canvas(master, width=100, height=100) glycan_image = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(figure_w / 2, figure_h / 2, image=glycan_image, tags=counter) canvas.bind("<Button-1>", self.clicked_glycan) canvas.bind("<Double-Button-1>", self.select_glycan) self.glycan_balloon.bind( canvas, 'Name: ' + name + '\nStructure: ' + self.myDrawer.tree_to_text(tree, root, names, visited=[])) tkagg.blit(glycan_image, figure_canvas_agg.get_renderer()._renderer, colormode=2) canvas.grid(column=j, row=i) glycan_images.append(glycan_image) glycan_canvas.append(canvas) j += 1 counter += 1
def draw(self): FigureCanvasAgg.draw(self) tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2) self._master.update_idletasks()
def Draw(self, fig_photo): # Unfortunately, there's no accessor for the pointer to the native renderer self.fig_photo = fig_photo tkagg.blit(self.fig_photo, self.figure_canvas_agg.get_renderer()._renderer, colormode=2)
def blit(self, bbox=None): tkagg.blit(self._tkphoto, self.renderer._renderer, bbox=bbox, colormode=2) self._master.update_idletasks()
def main(): fig = Figure() ax = fig.add_subplot(111) ax.set_xlabel("X axis") ax.set_ylabel("Y axis") ax.grid() # define the form layout layout = [[ sg.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20') ], [sg.Canvas(size=(640, 480), key='canvas')], [ sg.Slider(range=(0, 10000), size=(60, 10), orientation='h', key='slider') ], [ sg.ReadButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14') ]] # create the form and show it without the plot window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI' ).Layout(layout).Finalize() canvas_elem = window.FindElement('canvas') slider_elem = window.FindElement('slider') graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas) canvas = canvas_elem.TKCanvas dpts = [randint(0, 10) for x in range(10000)] for i in range(len(dpts)): button, values = window.ReadNonBlocking() if button is 'Exit' or values is None: exit(69) slider_elem.Update(i) ax.cla() ax.grid() DATA_POINTS_PER_SCREEN = 40 ax.plot(range(DATA_POINTS_PER_SCREEN), dpts[i:i + DATA_POINTS_PER_SCREEN], color='purple') graph.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(640 / 2, 480 / 2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
def refresh_canvas(canvas_pack): ax, fig, fig_photo, fig_canvas_agg = canvas_pack fig.canvas.draw() tkagg.blit(fig_photo, fig_canvas_agg.get_renderer()._renderer, colormode=2)