def __get_column_width(self): max_length = 0 max_column_text = '' flag = self.prefs.get('legend_numbers',True) unit = self.prefs.get('legend_unit',False) for label,num in self.labels: if not flag: num = None if num is not None: column_length = len(str(label)+str(num)) + 1 else: column_length = len(str(label)) + 1 if column_length > max_length: max_length = column_length if flag: if type(num) == types.IntType or type(num) == types.LongType: numString = str(num) else: numString = "%.1f" % float(num) max_column_text = '%s %s' % (str(label),numString) if unit: max_column_text += "%" else: max_column_text = '%s ' % str(label) figure = Figure() canvas = FigureCanvasAgg(figure) dpi = self.prefs['dpi'] figure.set_dpi( dpi ) l_size,l_padding = self.__get_legend_text_size() self.text_size = pixelToPoint(l_size,dpi) text = Text(0.,0.,text=max_column_text,size=self.text_size) text.set_figure(figure) bbox = text.get_window_extent(canvas.get_renderer()) self.column_width = bbox.width+6*l_size
def print_png(self, filename, *args, **kwargs): '''Call the widget function to make a png of the widget. ''' fig = FigureCanvasAgg(self.figure) FigureCanvasAgg.draw(fig) l, b, w, h = self.figure.bbox.bounds texture = Texture.create(size=(w, h)) texture.blit_buffer(bytes(fig.get_renderer().buffer_rgba()), colorfmt='rgba', bufferfmt='ubyte') texture.flip_vertical() img = Image(texture) img.save(filename)
def get_renderer(fig): if fig._cachedRenderer: renderer = fig._cachedRenderer else: canvas = fig.canvas if canvas and hasattr(canvas, "get_renderer"): renderer = canvas.get_renderer() else: # not sure if this can happen warnings.warn("tight_layout : falling back to Agg renderer") from matplotlib.backends.backend_agg import FigureCanvasAgg canvas = FigureCanvasAgg(fig) renderer = canvas.get_renderer() return renderer
def get_renderer(fig): if fig._cachedRenderer: renderer = fig._cachedRenderer else: canvas = fig.canvas if canvas and hasattr(canvas, "get_renderer"): renderer = canvas.get_renderer() else: # not sure if this can happen # seems to with PDF... _log.info("constrained_layout : falling back to Agg renderer") from matplotlib.backends.backend_agg import FigureCanvasAgg canvas = FigureCanvasAgg(fig) renderer = canvas.get_renderer() return renderer
def get_renderer(fig): if fig._cachedRenderer: renderer = fig._cachedRenderer else: canvas = fig.canvas if canvas and hasattr(canvas, "get_renderer"): renderer = canvas.get_renderer() else: # not sure if this can happen # seems to with PDF... _log.info("constrained_layout : falling back to Agg renderer") from matplotlib.backends.backend_agg import FigureCanvasAgg canvas = FigureCanvasAgg(fig) renderer = canvas.get_renderer() return renderer
def get_renderer(fig): if fig._cachedRenderer: renderer = fig._cachedRenderer else: canvas = fig.canvas if canvas and hasattr(canvas, "get_renderer"): renderer = canvas.get_renderer() else: # not sure if this can happen warnings.warn("tight_layout : falling back to Agg renderer") from matplotlib.backends.backend_agg import FigureCanvasAgg canvas = FigureCanvasAgg(fig) renderer = canvas.get_renderer() return renderer
def draw_glycoprotein(self, chid): """Draws 2D representation of glycoprotein in right panel Updates glycoprotein_2D canvas Parameters: chid: chain id (string or handle) """ fig = mpl.figure.Figure(figsize=(300 / self.dpi, 1000 / self.dpi), dpi=100) ax = fig.add_axes([0, 0, 1, 1]) if type(chid) is not str: chid = chid.get() l = len(self.myGlycosylator.sequences[chid]) trees = self.original_glycans.copy() trees.update(self.linked_glycans) sequons = [ k for k in self.myGlycosylator.sequons.keys() if chid in k[:len(chid)] ] self.myDrawer.draw_glycoprotein( l, self.myGlycosylator.get_start_resnum(chid), sequons, ax=ax, axis=1, trees=trees, names=self.names, sequon_color=self.sequon_colors) ax.axis('equal') ax.axis('off') 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) # attaching figure to canvas self.glycoprotein_image = tk.PhotoImage(master=self.glycan_2D, width=figure_w, height=figure_h) self.glycoprotein_2D.create_image(figure_w / 2, figure_h / 2, image=self.glycoprotein_image) tkagg.blit(self.glycoprotein_image, figure_canvas_agg.get_renderer()._renderer, colormode=2)
class Histplot2d: def __init__(self, X, Y, Y_fit, labels={}): if not labels: labels = {'title': 'Histogram', 'X': 'G', 'Y': 'counts'} # Large arrays kill matplotlib if len(X) % 2: X = X[:-1] Y = Y[:-1] while len(X) > 10000: newlen = int(len(X) / 2) _x = X.reshape(-1, newlen) _y = Y.reshape(-1, newlen) X = _x.reshape(-1, newlen).mean(axis=1) Y = _y.reshape(-1, newlen).mean(axis=1) #>>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated', #... aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) #>>> im = NonUniformImage(ax, interpolation='bilinear') #>>> xcenters = (xedges[:-1] + xedges[1:]) / 2 #>>> ycenters = (yedges[:-1] + yedges[1:]) / 2 #>>> im.set_data(xcenters, ycenters, H) #>>> ax.images.append(im) #>>> plt.show() Y = np.log10(Y) fig = mpl.figure.Figure(figsize=(5, 3.5), dpi=80) ax = fig.add_subplot(111) # ax.plot(X, Y_fit, lw=2.0, color='b', label='Fit') ax.bar(X, Y, width=0.000005, align='center', color='r') ax.set_xlabel(labels['X']) ax.set_ylabel('Log ' + labels['Y']) fig.suptitle(labels['title']) self.figure_canvas_agg = FigureCanvasAgg(fig) self.figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds self.figure_w, self.figure_h = int(figure_w), int(figure_h) 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) plt.show()
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_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)): 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 the photo object to keep the image alive return photo
def show_next_frame(self): # Clear figure to fit new one plt.gcf().clf() plt.gcf().set_dpi(100) plt.gcf().set_figwidth(6) plt.gcf().set_figheight(6) # Advance to next snapshot, or reset to beginning of loop self.data.next_data() # Generate next heatmap sns.heatmap(self.data.get_data(), vmin=0, vmax=np.amax(self.data.get_data()), cmap=self.cmap, xticklabels=False, yticklabels=False, square=1) plt.tight_layout(h_pad=0, w_pad=0) # show background plt.imshow(self.bg) plt.xticks([]) plt.yticks([]) ax = plt.gca() ax.set_xlim(0, self.bg.shape[1]) ax.set_ylim(self.bg.shape[0], 0) # Draw figure over background figure_canvas_agg = FigureCanvasAgg(plt.gcf()) figure_canvas_agg.draw() f_x, f_y, f_w, f_h = plt.gcf().bbox.bounds f_w, f_h = int(f_w), int(f_h) photo = tk.PhotoImage(master=self.canvas, width=f_w, height=f_h) # Position: convert from top-left anchor to center anchor self.canvas.create_image(f_w / 2, f_h / 2, image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) self.frame = photo # this handle must be kept alive # self.canvas.itemconfigure(self.date_label, text=self.data.get_date()) date_txt = self.data.get_date().strftime("%b %d, %Y") self.canvas.create_text((40, 70), anchor='nw', fill='#ffffff', text=date_txt)
def draw_figure(self, figure, loc=(0, 0)): 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=self.canv, width=figure_w, height=figure_h) self.canv.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 photo
def draw_glycan(self, sequon, *arg): """ Draws 2D representation of glycan of selected sequon Updates glycan_2D canvas Parameters: sequon: id of sequon """ fig = mpl.figure.Figure(figsize=(100./self.dpi, 100./self.dpi)) ax = fig.add_subplot(111) if type(sequon) is not str: sequon = sequon.get() if sequon in self.sequon_colors: color = self.sequon_colors[sequon] else: color = [.5, .5, .5] # Draw protein fragment self.myDrawer.draw_protein_fragment(ax = ax, sequon_color = color) # Drawing glycan glycan = True if sequon in self.linked_glycans: root,tree = self.linked_glycans[sequon] elif sequon in self.original_glycans: root,tree = self.original_glycans[sequon] else: self.myDrawer.draw_protein_fragment(ax = ax) glycan = False name = 'Structure: N/A' if glycan: self.myDrawer.draw_tree(tree, root, self.names, root_pos = [0, 0], direction = 1, ax = ax, axis = 0) name = 'Structure: ' + self.myDrawer.tree_to_text(tree, root, self.names, visited = []) ax.axis('equal') ax.axis('off') #ax.set_ylim((-3, 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) self.glycan_image = tk.PhotoImage(master=self.glycan_2D, width=figure_w, height=figure_h) self.glycan_2D.create_image(figure_w/2, figure_h/2, image=self.glycan_image) self.glycan_name.tagunbind(self.right_frame, self.glycan_2D) self.glycan_name.bind(self.glycan_2D, name) tkagg.blit(self.glycan_image, figure_canvas_agg.get_renderer()._renderer, colormode=2)
def get_image(self): width = self.extent[1] - self.extent[0] height = self.extent[3] - self.extent[2] self.figure.set_size_inches((6, 6. * width / height)) self.figure.set_dpi(self.settings.exportDpi) self.figure.patch.set_alpha(0) self.axes.axesPatch.set_alpha(0) canvas = FigureCanvasAgg(self.figure) canvas.draw() renderer = canvas.get_renderer() if matplotlib.__version__ >= '1.2': buf = renderer.buffer_rgba() else: buf = renderer.buffer_rgba(0, 0) size = canvas.get_width_height() image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) return image
def get_image(self): width = self.extent[1] - self.extent[0] height = self.extent[3] - self.extent[2] self.figure.set_size_inches((6, 6. * width / height)) self.figure.set_dpi(self.settings.exportDpi) self.figure.patch.set_alpha(0) self.axes.patch.set_alpha(0) canvas = FigureCanvasAgg(self.figure) canvas.draw() renderer = canvas.get_renderer() if matplotlib.__version__ >= '1.2': buf = renderer.buffer_rgba() else: buf = renderer.buffer_rgba(0, 0) size = canvas.get_width_height() image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) return image
class DepthProfileFigureCanvas(tk.Canvas): def __init__(self, master, profile_figure): tk.Canvas.__init__(self, master) self.figure = profile_figure self.redraw() def redraw(self): self.mpl_figure = self.figure.prepare() self.fc = FigureCanvas(self.mpl_figure) self.fc.draw() self.figure_x, self.figure_y, self.figure_w, self.figure_h = self.mpl_figure.bbox.bounds self.figure_w, self.figure_h = int(self.figure_w), int(self.figure_h) self.configure(width=self.figure_w, height=self.figure_h) self.photo = tk.PhotoImage(master=self, width=self.figure_w, height=self.figure_h) self.create_image(self.figure_w / 2, self.figure_h / 2, image=self.photo) tkagg.blit(self.photo, self.fc.get_renderer()._renderer, colormode=2)
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 export_image(filename, format, figure): oldSize = figure.get_size_inches() oldDpi = figure.get_dpi() figure.set_size_inches((8, 4.5)) figure.set_dpi(600) canvas = FigureCanvasAgg(figure) canvas.draw() renderer = canvas.get_renderer() if matplotlib.__version__ >= '1.2': buf = renderer.buffer_rgba() else: buf = renderer.buffer_rgba(0, 0) size = canvas.get_width_height() image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) image = image.convert('RGB') ext = File.get_export_ext(format, File.Exports.IMAGE) image.save(filename, format=ext[1::]) figure.set_size_inches(oldSize) figure.set_dpi(oldDpi)
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)): """ 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_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 __get_column_width(self): max_length = 0 max_column_text = "" flag = self.prefs.get("legend_numbers", True) unit = self.prefs.get("legend_unit", False) for label, num in self.labels: if not flag: num = None if num is not None: column_length = len(str(label) + str(num)) + 1 else: column_length = len(str(label)) + 1 if column_length > max_length: max_length = column_length if flag: if isinstance(num, six.integer_types): numString = str(num) else: numString = "%.1f" % float(num) max_column_text = "%s %s" % (str(label), numString) if unit: max_column_text += "%" else: max_column_text = "%s " % str(label) figure = Figure() canvas = FigureCanvasAgg(figure) dpi = self.prefs["dpi"] figure.set_dpi(dpi) l_size, _ = self.__get_legend_text_size() self.text_size = pixelToPoint(l_size, dpi) text = Text(0.0, 0.0, text=max_column_text, size=self.text_size) text.set_figure(figure) bbox = text.get_window_extent(canvas.get_renderer()) columnwidth = bbox.width + 6 * l_size # make sure the legend fit in the box self.column_width = (columnwidth if columnwidth <= self.prefs["legend_width"] else self.prefs["legend_width"] - 6 * l_size)
def __get_column_width(self): max_length = 0 max_column_text = '' flag = self.prefs.get('legend_numbers', True) unit = self.prefs.get('legend_unit', False) for label, num in self.labels: if not flag: num = None if num is not None: column_length = len(str(label) + str(num)) + 1 else: column_length = len(str(label)) + 1 if column_length > max_length: max_length = column_length if flag: if type(num) == types.IntType or type( num) == types.LongType: numString = str(num) else: numString = "%.1f" % float(num) max_column_text = '%s %s' % (str(label), numString) if unit: max_column_text += "%" else: max_column_text = '%s ' % str(label) figure = Figure() canvas = FigureCanvasAgg(figure) dpi = self.prefs['dpi'] figure.set_dpi(dpi) l_size, _ = self.__get_legend_text_size() self.text_size = pixelToPoint(l_size, dpi) text = Text(0., 0., text=max_column_text, size=self.text_size) text.set_figure(figure) bbox = text.get_window_extent(canvas.get_renderer()) columnwidth = bbox.width + 6 * l_size self.column_width = columnwidth if columnwidth <= self.prefs[ 'legend_width'] else self.prefs[ 'legend_width'] - 6 * l_size #make sure the legend fit in the box
class XYplot: #https://matplotlib.org/gallery/user_interfaces/embedding_in_tk_canvas_sgskip.html def __init__(self, X, Y, labels={}): if not labels: labels = {'title': 'XY Plot', 'X': 'distance', 'Y': 'current'} fig = mpl.figure.Figure(figsize=(5, 3.5), dpi=80) ax = fig.add_subplot(111) ax.plot(X, Y) ax.set_xlabel(labels['X']) ax.set_ylabel(labels['Y']) fig.suptitle(labels['title']) self.figure_canvas_agg = FigureCanvasAgg(fig) self.figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds self.figure_w, self.figure_h = int(figure_w), int(figure_h) 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 export_image(filename, format, figure, settings): oldSize = figure.get_size_inches() oldDpi = figure.get_dpi() figure.set_size_inches((settings.exportWidth, settings.exportHeight)) figure.set_dpi(settings.exportDpi) canvas = FigureCanvasAgg(figure) canvas.draw() renderer = canvas.get_renderer() if matplotlib.__version__ >= '1.2': buf = renderer.buffer_rgba() else: buf = renderer.buffer_rgba(0, 0) size = canvas.get_width_height() image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) image = image.convert('RGB') ext = File.get_type_ext(format, File.Types.IMAGE) image.save(filename, format=ext[1::], dpi=(settings.exportDpi, settings.exportDpi)) figure.set_size_inches(oldSize) figure.set_dpi(oldDpi)
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
class Histplot: def __init__(self, X, Y, Y_fit, labels={}): if not labels: labels = {'title': 'Histogram', 'X': 'G', 'Y': 'counts'} # Large arrays kill matplotlib if len(X) % 2: X = X[:-1] Y = Y[:-1] while len(X) > 10000: newlen = int(len(X) / 2) _x = X.reshape(-1, newlen) _y = Y.reshape(-1, newlen) X = _x.reshape(-1, newlen).mean(axis=1) Y = _y.reshape(-1, newlen).mean(axis=1) Y = np.log10(Y) fig = mpl.figure.Figure(figsize=(5, 3.5), dpi=80) ax = fig.add_subplot(111) # ax.plot(X, Y_fit, lw=2.0, color='b', label='Fit') ax.bar(X, Y, width=0.000005, align='center', color='r') ax.set_xlabel(labels['X']) ax.set_ylabel('Log ' + labels['Y']) fig.suptitle(labels['title']) self.figure_canvas_agg = FigureCanvasAgg(fig) self.figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds self.figure_w, self.figure_h = int(figure_w), int(figure_h) 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) plt.show()
def get_renderer(fig): """Get the renderer for a Matplotlib Figure. Args: fig (matplotlib.figure.Figure): [description] Returns: matplotlib.backend_bases.RendererBase: A Matplotlib renderer. """ if fig._cachedRenderer: renderer = fig._cachedRenderer else: canvas = fig.canvas if canvas and hasattr(canvas, "get_renderer"): renderer = canvas.get_renderer() else: # Some noninteractive backends have no renderer until draw time. from matplotlib.backends.backend_agg import FigureCanvasAgg canvas = FigureCanvasAgg(fig) renderer = canvas.get_renderer() return renderer
def __draw_image(self, sizeInches, ppi): oldSize = self.figure.get_size_inches() oldDpi = self.figure.get_dpi() self.figure.set_size_inches(sizeInches) self.figure.set_dpi(ppi) canvas = FigureCanvasAgg(self.figure) canvas.draw() renderer = canvas.get_renderer() if matplotlib.__version__ >= '1.2': buf = renderer.buffer_rgba() else: buf = renderer.buffer_rgba(0, 0) size = canvas.get_width_height() image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) self.figure.set_size_inches(oldSize) self.figure.set_dpi(oldDpi) imageWx = wx.EmptyImage(image.size[0], image.size[1]) imageWx.SetData(image.convert('RGB').tostring()) return imageWx
def __draw_image(self, sizeInches, ppi): oldSize = self.figure.get_size_inches() oldDpi = self.figure.get_dpi() self.figure.set_size_inches(sizeInches) self.figure.set_dpi(ppi) canvas = FigureCanvasAgg(self.figure) canvas.draw() renderer = canvas.get_renderer() if matplotlib.__version__ >= '1.2': buf = renderer.buffer_rgba() else: buf = renderer.buffer_rgba(0, 0) size = canvas.get_width_height() image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) self.figure.set_size_inches(oldSize) self.figure.set_dpi(oldDpi) imageWx = wx.Image(image.size[0], image.size[1]) imageWx.SetData(image.convert('RGB').tobytes()) return imageWx
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 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 make_png(md5hash, cmap='gray', sigma=1.0, crop=False, options='', annotation=''): """Create a PNG stamp from a FITS file. :param md5hash: :param cmap: :param sigma: :param crop: :param options: :param annotation: :return: """ outFile = md5hash # Read fitsim = maputils.FITSimage(outFile+'.fit') fig = Figure(figsize=(5,5), facecolor="#ffffff") canvas = FigureCanvas(fig) frame = fig.add_subplot(1,1,1) # Work out scaling dat = fitsim.dat.ravel() dat = dat.compress(dat>0.0) if len(dat)>10: z1, z2 = astats.zscale(dat, nsample=min(1000,len(dat))) else: z1 = z2 = 0.0 # Options cmapinverse=False if ('H' in options): cmap='hot' if ('W' in options): cmap='winter' if ('I' in options): cmap=cmap+'_r' annim = fitsim.Annotatedimage(frame, cmap=cmap.replace('_r',''), clipmin=z1, clipmax=z2*sigma) if cmap.find('_r')>0: annim.cmap.set_inverse(True) annim.Image() # Work out grid a,d = fitsim.convproj.toworld(((0,0),(0,fitsim.hdr['NAXIS2']))) b = numpy.array([5,10,15,20,25,30,35,40,45,50,55,60]) j = b.searchsorted(int(math.sqrt((a[0]-a[1])**2+(d[0]-d[1])**2)*3600.)/6) deltay = b[j] grat = annim.Graticule( starty=fitsim.hdr['CRVAL2'], deltay=deltay/3600., startx=fitsim.hdr['CRVAL1'], deltax=deltay/3600./math.cos(math.radians(d[0]))) grat.setp_lineswcs0(visible=False) grat.setp_lineswcs1(visible=False) grat.setp_plotaxis(0, mode=0, label='') grat.setp_plotaxis(1, mode=0, label='') grat.setp_plotaxis(2, mode=0, label='') grat.setp_plotaxis(3, mode=0, label='') grat.setp_tick(visible=False) grat.setp_tickmark(color='#99FF99', markersize=4, markeredgewidth=2) # Plot center cross xcen, ycen = fitsim.hdr['NAXIS1']/2.+0.5,fitsim.hdr['NAXIS2']/2.+0.5 frame.plot([xcen,xcen],[ycen/6.,ycen-ycen/6.],linewidth=1,color='#99FF99') frame.plot([xcen,xcen],[ycen+ycen/6.,ycen*2-ycen/6.],linewidth=1,color='#99FF99') frame.plot([xcen/6.,xcen-xcen/6.],[ycen,ycen],linewidth=1,color='#99FF99') frame.plot([xcen+ycen/6.,xcen*2-ycen/6.],[ycen,ycen],linewidth=1,color='#99FF99') annim.plot() if (annotation): frame.fill([0.001,0.999,0.999,0.001], [0.999,0.999,0.90-0.08, 0.90-0.08], transform = frame.transAxes, edgecolor='none', facecolor='#000000', alpha=0.4) i = 0 for item in annotation.split('\\n'): frame.text(0.04,0.92-i*0.06, item, transform = frame.transAxes, color='#FFFFFF') i = i + 1 canvas.draw() if crop: size = canvas.get_renderer().get_canvas_width_height() buf = canvas.tostring_rgb() im = PILImage.fromstring('RGB', map(int, size), buf, 'raw', 'RGB', 0, 1) im2 = im.convert('L'); im2 = PILImageOps.invert(im2) im=im.crop(im2.getbbox()) im.save(outFile+'.png', 'PNG') else: s = StringIO.StringIO() canvas.print_png(s) s.flush() s.seek(0) open(outFile+'.png','w').write(s.read()) time.sleep(0.25)
def plot_gamma_dist(Ymes, Ypre, fname, language='English'): fw, fh = 6, 6 fig = mpl.figure.Figure(figsize=(fw, fh), facecolor='white') canvas = FigureCanvas(fig) # ---- Create Axes leftMargin = 1.1 / fw rightMargin = 0.25 / fw bottomMargin = 0.85 / fh topMargin = 0.25 / fh x0 = leftMargin y0 = bottomMargin w0 = 1 - (leftMargin + rightMargin) h0 = 1 - (bottomMargin + topMargin) ax0 = fig.add_axes([x0, y0, w0, h0]) ax0.set_yscale('log', nonposy='clip') Xmax = max(np.ceil(np.max(Ymes)/10.) * 10, 80) # ---- Plots c1, c2 = '#6495ED', 'red' if language == 'French': lg_labels = [u'DP des données mesurées', u'FDP Gamma (mesurée)', u'FDP Gamma (estimée)'] else: lg_labels = ['Measured data PDF', 'Gamma PDF (measured)', 'Gamma PDF (estimated)'] # Histogram ax0.hist(Ymes, bins=20, color=c1, histtype='stepfilled', density=True, alpha=0.25, ec=c1, label=lg_labels[0]) # Measured Gamma PDF alpha, loc, beta = gamma.fit(Ymes) x = np.arange(0.5, Xmax, 0.1) ax0.plot(x, gamma.pdf(x, alpha, loc=loc, scale=beta), '-', lw=2, alpha=1., color=c1, label=lg_labels[1]) # Predicted Gamma PDF alpha, loc, beta = gamma.fit(Ypre) x = np.arange(0.5, Xmax, 0.1) ax0.plot(x, gamma.pdf(x, alpha, loc=loc, scale=beta), '--r', lw=2, alpha=0.85, color=c2, label=lg_labels[2]) # ---- Axis Limits ax0.axis(xmin=0, xmax=Xmax, ymax=1) # ---- Labels # Setup axis labels if language == 'French': ax0.set_xlabel(u'Précipitations totales journalières (mm)', fontsize=18, labelpad=15) ax0.set_ylabel('Probabilité', fontsize=18, labelpad=15) else: ax0.set_xlabel('Daily Total Precipitation (mm)', fontsize=18, labelpad=15) ax0.set_ylabel('Probability', fontsize=18, labelpad=15) # Setup yticks labels ax0.xaxis.set_ticks_position('bottom') ax0.yaxis.set_ticks_position('left') ax0.tick_params(axis='both', direction='out', labelsize=14) ax0.tick_params(axis='both', which='minor', direction='out', labelsize=14) canvas.draw() ylabels = [] for i, label in enumerate(ax0.get_yticks()): if label >= 1: ylabels.append('%d' % label) elif label <= 10**-3: ylabels.append('$\\mathdefault{10^{%d}}$' % np.log10(label)) else: ylabels.append(str(label)) ax0.set_yticklabels(ylabels) # ---- Legend lg = ax0.legend(loc='upper right', frameon=False) # ---- Wet Days Comparison -- # ---- Generate text preWetDays = np.where(Ypre > 0)[0] mesWetDays = np.where(Ymes > 0)[0] f = len(preWetDays) / float(len(mesWetDays)) * 100 if f > 100: if language == 'French': msg = 'Nombre de jours pluvieux surestimé de %0.1f%%' % (f - 100) else: msg = 'Number of wet days overestimated by %0.1f%%' % (f - 100) else: if language == 'French': msg = 'Nombre de jours pluvieux sous-estimé de %0.1f%%' % (100 - f) else: msg = 'Number of wet days underestimated by %0.1f%%' % (100 - f) # ---- Get Legend Box Position and Extent canvas.draw() bbox = lg.get_window_extent(canvas.get_renderer()) bbox = bbox.transformed(ax0.transAxes.inverted()) dx, dy = 5/72., 5/72. padding = mpl.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) transform = ax0.transAxes + padding ax0.text(0., 0., msg, transform=transform, va='bottom', ha='left') # ---- Draw fig.savefig(fname) # A canvas.draw() is included with this. return canvas
class Bars: """This class represents a complex horizontal bar chart. This class extends (by composition) the functionality provided by Matplotlib. The chart is automatically rendered in Jupyter notebooks and can be saved on disk. The chart can be tailored to a great extent by passing keyword arguments to the constructor. (SEE the class attribute **Bars.conf** for listing the other optional **kwargs**). If it is not enough, the **conf.py** module in the Catbars package gives users full control over "rcParams". Parameters ----------- numbers : iterable container The numbers specifying the width of each bar. First numbers are converted into bars appearing on the top of the figure. left_labels : iterable container or str, optional Labels associated with the bars on the left. The "rank" option creates one-based indices. The "proportion" option creates labels representing the relative proportion of each bar in percents. "rank" and "proportion" labels depend on the "slice" unless "global_view" is True. right_labels : iterable container or str, optional Labels associated with the bars on the right. It accepts the same values as "left_labels". colors : iterable container, optional The container items can be of any type. Bar colors are automatically inferred in function of the available "tints" (SEE Bars.conf) and the most common items in the "slice" (unless "global_view is True). If there are more distinct items than available "tints", "default_color" and "default_label" are used with residual items. The automatic color selection can be overriden by "color_dic". line_dic : dict, optional This dictionary has to contain three keys: "number", "color" and "label". It describes an optional vertical line to draw. sort : bool, optional If True, "numbers" are sorted in descending order. Optional labels and the "colors" parameter are sorted in the same way. The default value is False. slice : tuple : (start,stop), optional start and stop are one-based indices. Slicing precedes sorting unless "global_view" is True. global_view : bool, optional If True, the whole dataset is considered instead of the optional slice when sorting, coloring, setting x bounds and creating "rank" and "proportion" labels. The default value is False. auto_scale : bool, optional If True, the logarithmic scale is used when it seems better for readability. The default value is False. color_dic : dict, optional A dictionary mapping "colors" items (keys) to Matplotlib colors (values)."colors" items which are not specified by the dic. are treated as residual items (SEE "colors"). title : str, optional Figure title. xlabel : str, optional The Matplotlib xlabel. ylabel : str, optional The Matplotlib ylabel. legend_title : str, optional legend_visible : bool, optional The default value is True. figsize : (width, height), optional The Matplotlib figsize. The default value is (6,5). dpi : number, optional The Matplotlib dpi. The default value is 100. file_name : str or path-like or file-like object The path of the png file to write to. (SEE the method print_pdf() for writing pdf files). Returns -------- catbars.bars.Bars A Bars instance. It encapsulates useful Matplotlib objects. Attributes ----------- conf : dict This class attribute contains the advanced optional constructor parameters along with their current values. In particular, it contains the "fig_size", "dpi", "tints", "default_color" and "default_label" values. fig : matplotlib.figure.Figure ax : matplotlib.axes.Axes canvas : matplotlib.backends.backend_agg.FigureCanvasAgg data : catbars.models.AbstractModel The Bars class delegates to another class data processing tasks. Methods ------- print_png(file_name) To write png files. print_pdf(file_name) To write pdf files. """ conf = Conf.conf def __init__(self, numbers, left_labels = None, right_labels = None, # 'proportion' 'rank' colors = None, line_dic = None, sort = False, slice = None, # one-based indexing global_view = False, auto_scale = False, color_dic = None, title = None, xlabel = None, ylabel = None, legend_title = None, legend_visible = True, file_name = None, **kwargs): """ The data space can adapt to long labels but only to some extent because the long label sizes are fixed. This class moves the edges of the axes to make room for labels (SEE Matplotlib HOW-TOs). """ if 'log_level' in kwargs: logging.basicConfig(format='{levelname}:\n{message}', level= getattr(logging, kwargs['log_level']), style = '{') # Configuration: matplotlibrc is decorated by conf.py. self.conf = Conf.change_conf(kwargs) # Data formatted by the model. self.data = None # Core Matplotlib objects. self.fig = None self.ax = None self.canvas = None self.vertical_line = None self.bars = None # BarContainer. self._virtual_bars = None # For global_view. # Helper attributes. self._left_label_data = None self._right_label_texts = None # Titles. self.title = title self.xlabel = xlabel self.ylabel = ylabel self.legend_title = legend_title self._global_view = global_view self.legend = None self._legend_width = 0 self.legend_visible = legend_visible # The vertical line. self.line_x = None self.line_label = None self.line_color = None # Original position of the axes edges in the figure. self._x0 = 0 self._y0 = 0 self._width = 1 self._height = 1 # To deal with not square figures, # only x sizes are adapted. self._x_coeff = 1 ######################################################### # Model. factory = ModelFactory( numbers, global_view = global_view, left_labels = left_labels, right_labels = right_labels, colors = colors, sort = sort, slice = slice, default_label = self.conf['default_label'], color_dic = color_dic, tints = self.conf['tints'], default_color = self.conf['default_color']) self.data = factory.model self.fig = Figure(figsize = self.conf['figsize'], dpi = self.conf['dpi']) self.canvas = FigureCanvasAgg(self.fig) self.ax = Axes(self.fig, [self._x0, self._y0, self._width, self._height]) self.fig.add_axes(self.ax) self.canvas.draw() w, h = self.fig.get_size_inches() self._x_coeff = h / w # margin. margin = self.conf['margin'] self._x0 = self._x_coeff * margin self._y0 = margin self._width = self._width - 2 * self._x_coeff * margin self._height = self._height - 2 * margin self._set_position() self.ax.tick_params(axis = 'y', length = 0) self.ax.grid(b = True, axis = 'x', which = 'both', color = 'black', alpha = 0.3) for name in ['top', 'right']: self.ax.spines[name].set_visible(False) # xscale. if auto_scale is True: # To improve clarity. if self.data.spread > 1 or self.data.maximum > 1e6: self.ax.set(xscale = 'log') else: default_formatter = self.ax.get_xaxis().get_major_formatter() custom_formatter = self.build_formatter(default_formatter) formatter = matplotlib.ticker.FuncFormatter(custom_formatter) self.ax.get_xaxis().set_major_formatter(formatter) # Title. if self.title is not None: self._manage_title() _kwargs = dict() # Left labels. if self.data.left_labels is not None: _kwargs['tick_label'] = self.data.left_labels else: _kwargs['tick_label'] = '' # colors. if self.data.actual_colors is not None: _kwargs['color'] = self.data.actual_colors else: _kwargs['color'] = self.data.default_color # bars. self.bars = self.ax.barh(list(range(self.data.length)), self.data.numbers, height = 1, edgecolor = 'white', linewidth = 1, # 0.4 alpha = self.conf['color_alpha'], **_kwargs) # To fix x bounds, virtual bars are used. if self._global_view is True: self._virtual_bars = self.ax.barh( [0, 0], [self.data.minimum, self.data.maximum], height = 0.5, edgecolor = 'white', linewidth = 1, # 0.4 alpha = self.conf['color_alpha'], visible = False) # The vertical line. if line_dic is not None: self._set_line(line_dic) if (self.line_x is not None and self.data.minimum <= self.line_x <= self.data.maximum): # self.vertical_line = self.ax.axvline( self.line_x, ymin = 0, ymax = 1, color = self.line_color, linewidth = 2, alpha = self.conf['color_alpha']) # Left label constraint solving. self._make_room_for_left_labels() # ylabel. if self.ylabel is not None: self._manage_ylabel() # Legend. if (self.legend_visible is True and self.data.colors is not None): # self._draw_legend() self._make_room_for_legend() # Right labels. if self.data.right_labels is not None: self._draw_right_labels() self._make_room_for_right_labels() min_tick_y = self._clean_x_ticklabels() # xlabel. if self.xlabel is not None: self._manage_xlabel(min_tick_y) else: delta_y0 = abs(self._y0 - min_tick_y) self._y0 = self._y0 + delta_y0 self._height = self._height - delta_y0 self._set_position() self.canvas.draw() # Printing. if file_name is not None: self.canvas.print_png(file_name) ############################################################# def _set_line(self, line_dic): try: self.line_x = line_dic['number'] self.line_label = line_dic['label'] self.line_color = line_dic['color'] except Exception: text = """ "line_dic" has to define three keys: 'number', 'label' and 'color'. """ raise TypeError(text.strip()) def _manage_title(self): pad_in_points = self.fig_coord_to_points(self.fig, self.conf['title_pad'], axis = 'y') title_label = self.ax.set_title( self.title, pad = pad_in_points, fontsize = self.conf['title_font_size'], fontweight = 'bold') self.canvas.draw() h = title_label.get_window_extent( renderer = self.canvas.get_renderer() ).height h_in_fig_coord = self.disp_to_fig_coord(self.fig, h, axis = 'y') total_h = (h_in_fig_coord + self.conf['title_pad']) self._height = self._height - total_h self._set_position() def _make_room_for_left_labels(self): """ Constraint solving for left labels. "left_label_data" is stored for further processing and will be used to align left and right labels. """ left_label_data = [] # To align left and right labels. min_x = None self.canvas.draw() for left_label in self.ax.get_yticklabels(): x, y = left_label.get_position() va = left_label.get_va() bbox = left_label.get_window_extent( renderer = self.canvas.get_renderer() ) inv = self.fig.transFigure.inverted() lab_x, _ = inv.transform((bbox.x0, bbox.y0)) if min_x is None or lab_x < min_x: min_x = lab_x # In pixels. left_label_data.append((y, va)) delta_x0 = abs(self._x0 - min_x) self._x0 = self._x0 + delta_x0 self._width = self._width - delta_x0 self._set_position() self._left_label_data = left_label_data def _manage_ylabel(self): """ """ pad = self.fig_coord_to_points(self.fig, self._x_coeff * self.conf['pad']) y_label = self.ax.set_ylabel( self.ylabel, labelpad = pad, fontweight = 'bold', fontsize = self.conf['axis_title_font_size']) self.canvas.draw() bbox = y_label.get_window_extent( renderer = self.canvas.get_renderer() ) w_in_fig_coord = self.disp_to_fig_coord(self.fig, bbox.width) delta_x0 = (w_in_fig_coord + self._x_coeff * self.conf['pad']) self._x0 = self._x0 + delta_x0 self._width = self._width - delta_x0 self._set_position() def _draw_legend(self): artists = [] labels = [] for i, color in enumerate(self.data.legend_colors): # Proxy artists. patch = mpatches.Patch(facecolor = color, alpha = self.conf['color_alpha']) artists.append(patch) labels.append(self.data.legend_labels[i]) if self.vertical_line is not None: artists.append(self.vertical_line) labels.append(self.line_label) kwargs = dict() if self.legend_title is not None: kwargs['title'] = self.legend_title lgd = self.fig.legend(artists, labels, loc ='center left', frameon = False, labelspacing = 0.25, borderpad = 0, borderaxespad = 0, prop = { 'size' : self.conf['axis_title_font_size']}, **kwargs) lgd.get_title().set_fontsize(self.conf['axis_title_font_size']) lgd.get_title().set_fontweight('bold') lgd.get_title().set_multialignment('center') self.canvas.draw() # Constraint solving. lgd_width = (lgd.get_window_extent( renderer = self.canvas.get_renderer() ).width) lgd_width_in_fig_coord = self.disp_to_fig_coord(self.fig, lgd_width) self.legend = lgd self._legend_width = lgd_width_in_fig_coord logging.info('legend width in pixels {}\n'.format(lgd_width)) def _make_room_for_legend(self): self.legend.set_bbox_to_anchor((1 - self._legend_width - self._x_coeff * self.conf['margin'], 0.5)) self._width = (self._width - self._legend_width - self._x_coeff *self.conf['pad']) self._set_position() def _draw_right_labels(self): """ Right labels. """ right_label_texts = [] for i, bar in enumerate(self.bars): y, va = self._left_label_data[i] w = bar.get_width() t = None if self.data.right_labels is not None: a_right_label = self.data.right_labels[i] text = ' {}'.format(a_right_label) t = self.ax.text(w, y, text, verticalalignment = va, fontweight = 'normal', zorder = 10) right_label_texts.append(t) self.canvas.draw() self._right_label_texts = right_label_texts def _make_room_for_right_labels(self): """ Constraint solving in figure coordinates. A bisection technique is used. """ def _objective_function(coeff_array, label_array, x): # return max(x, max(coeff_array * x + label_array)) bar_coeff = [] text_widths = [] for i, bar in enumerate(self.bars): bar_coeff.append(self._get_bar_coeff(bar)) t = self._right_label_texts[i] text_widths.append(self._get_text_width(t)) coeff_array = np.array(bar_coeff) label_array = np.array(text_widths) f = partial(_objective_function, coeff_array, text_widths) min_w = self.conf['min_ax_width'] max_it = self.conf['right_label_max_it'] tolerance = self.conf['right_label_solver_tolerance'] # Two special cases. if f(self._width) == self._width: pass # To check whether a solution exists. elif f(min_w) < self._width: w_b = self._width w_a = min_w i = 0 # To prevent from infinite loops. while abs(w_b - w_a) > tolerance and i < max_it: new_w = w_a + (w_b - w_a) / 2 if f(new_w) < self._width: w_a = new_w else: w_b = new_w logging.info('w_a {}\nw_b {}\n'.format(w_a, w_b)) i += 1 self._width = w_a else: self._width = min_w self._set_position() if i == max_it: logging.warning(""" right_label_max_it {} has been hit. """.format(max_it)) def _get_bar_coeff(self, bar): """ bar_width_in_ax_coord can't be greater than 0.95 if xmargin = 0.05. """ data_x_one = bar.get_bbox().x1 # Assuming that x0 = 0. disp_x_one, _ = self.ax.transData.transform((data_x_one, 0)) inv = self.ax.transAxes.inverted() bar_width_in_ax_coord, _ = inv.transform((disp_x_one, _)) return bar_width_in_ax_coord def _get_text_width(self, t): t_width = t.get_window_extent( renderer = self.canvas.get_renderer() ).width # In pixels. return self.disp_to_fig_coord(self.fig, t_width) def _clean_x_ticklabels(self): """ To discard overlaps. """ self.canvas.draw() labels = self.get_visible_ticklabels( self.ax, self.ax.xaxis.get_ticklabels(which = 'both') ) label_bboxes = [lab.get_window_extent( renderer = self.canvas.get_renderer() ) for lab in labels] current_bbox = label_bboxes[-1] min_tick_y = current_bbox.y0 for i in range(len(label_bboxes) - 1, 0, -1): if label_bboxes[i-1].overlaps(current_bbox): labels[i-1].set_visible(False) else: current_bbox = label_bboxes[i-1] if current_bbox.y0 < min_tick_y: min_tick_y = current_bbox.y0 inv = self.fig.transFigure.inverted() _, tick_y = inv.transform((0, min_tick_y)) return tick_y def _manage_xlabel(self, min_tick_y): """ min_tick_y is negative. """ pad = self.fig_coord_to_points(self.fig, self.conf['pad'], axis = 'y') x_label = self.ax.set_xlabel( self.xlabel, labelpad = pad, fontweight = 'bold', fontsize = self.conf['axis_title_font_size']) self.canvas.draw() bbox = x_label.get_window_extent( renderer = self.canvas.get_renderer() ) h = self.disp_to_fig_coord(self.fig, bbox.height, axis = 'y') delta_y0 = abs(self._y0 - min_tick_y) + h + self.conf['pad'] self._y0 = self._y0 + delta_y0 self._height = self._height - delta_y0 self._set_position() self.canvas.draw() def _set_position(self): self.ax.set_position([self._x0, self._y0, self._width, self._height]) positions = ['x0', 'y0', 'width', 'height'] text = 'Position of the Axes instance edges\n' for pos in positions: text = text + '{} {}\n'.format(pos, getattr(self, '_'+pos)) logging.info(text) def disp_to_fig_coord(self, fig, dist, axis = 'x'): """ Conversion of a distance from display coordinates to figure coordinates. """ w, h = fig.get_size_inches() if axis == 'x': return dist / (fig.dpi * w) else: return dist / (fig.dpi * h) def points_to_fig_coord(self, fig, points, axis = 'x'): """ axis = 'x' refers to the X axis ('y' corresponds to the Y axis). There are 72 points per inch. """ w, h = fig.get_size_inches() if axis == 'x': return (points * 1 / 72) / w else: return (points * 1 / 72) / h def fig_coord_to_points(self, fig, fraction, axis = 'x'): """ axis = 'x' refers to the X axis ('y' corresponds to the Y axis). Conversion from figure coordinates to points. """ w, h = fig.get_size_inches() if axis == 'x': return fraction * w * 72 else: return fraction * h * 72 def get_visible_ticklabels(self, ax, labels): """ Only a part of the built labels are displayed by the Matplotlib machinary. """ visible_labels = [] x_min, x_max = ax.get_xlim() for label in labels: x = label.get_position()[0] if x_min <= x <= x_max: if label.get_visible() and label.get_text(): visible_labels.append(label) return visible_labels def build_formatter(self, default_formatter): """ Custom scientific notation. """ def f(default_f, x, pos): if x > 1e6 or x < 1e-3: text = '{:.1e}'.format(x) n, e = text.split('e') if float(n) == 0: return 0 e = '{'+ e.lstrip('0+') + '}' label = r'${} \times 10^{}$'.format(n, e) return label else: return default_f(x, pos) return partial(f, default_formatter) def print_pdf(self, file_name): from matplotlib.backends.backend_pdf import PdfPages pp = PdfPages(file_name) pp.savefig(figure = self.fig) pp.close() def print_png(self, file_name): self.canvas.print_png(file_name) def _repr_png_(self): """ For notebook integration. """ w, h = self.fig.get_size_inches() buf = BytesIO() # In-memory bytes buffer. self.canvas.print_png(buf) return (buf.getvalue(), {'width' : str(w * self.fig.dpi), 'height': str(h * self.fig.dpi)})
def __plot(self, mousePos=None): figure, axes = plt.subplots() dpi = figure.get_dpi() viewSize = self._graphicsView.size() scrollSize = self._graphicsView.style().pixelMetric(QtGui.QStyle.PM_ScrollBarExtent) size = QtCore.QSize(viewSize.width() * self._scale - scrollSize, viewSize.height() * self._scale - scrollSize) figure.set_size_inches(size.width() / float(dpi), size.height() / float(dpi)) figure.patch.set_facecolor('w') plt.title('Signals') plt.xlabel('Frequency (MHz)') plt.ylabel('Detections') plt.grid(True) if matplotlib.__version__ >= '1.2': figure.tight_layout() renderer = plt.gcf().canvas.get_renderer() formatter = ScalarFormatter(useOffset=False) axes.xaxis.set_major_formatter(formatter) axes.yaxis.set_major_formatter(formatter) if self._show_all: signals = self._signals else: signals = [signal for signal in self._signals if signal[0] not in self._filtered] x, z, y, _levels = zip(*signals) x = [freq / 1e6 for freq in x] if len(x) > 2: width = min(numpy.diff(x)) / 2. else: width = 20 / 1e6 bars = axes.bar(x, y, width=width, color='blue') xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() for i in range(len(y)): bar = bars[i] freq = x[i] rate = z[i] height = bar.get_height() text = axes.text(bar.get_x() + width / 2., height, '{:.4f} ({:.1f})'.format(freq, rate), rotation=45, ha='left', va='bottom', size='smaller') if matplotlib.__version__ >= '1.3': effect = patheffects.withStroke(linewidth=2, foreground="w", alpha=0.75) text.set_path_effects([effect]) bounds = text.get_window_extent(renderer) bounds = bounds.transformed(axes.transData.inverted()) extents = bounds.extents xmin = min(xmin, extents[0]) ymin = min(ymin, extents[1]) xmax = max(xmax, extents[2]) ymax = max(ymax, extents[3]) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) canvas = FigureCanvasAgg(figure) canvas.draw() renderer = canvas.get_renderer() if matplotlib.__version__ >= '1.2': rgba = renderer.buffer_rgba() else: rgba = renderer.buffer_rgba(0, 0) image = QtGui.QImage(rgba, size.width(), size.height(), QtGui.QImage.Format_ARGB32) pixmap = QtGui.QPixmap.fromImage(image) scene = QtGui.QGraphicsScene(self) scene.addPixmap(pixmap) scene.setSceneRect(image.rect()) self._graphicsView.setScene(scene) if mousePos is not None: self._graphicsView.centerOn(mousePos.x() * self._scale, mousePos.y() * self._scale) plt.close()
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 plot_est_err(Ymes, Ypre, varName, fname, language='English'): Ymax = np.ceil(np.max(Ymes)/10)*10 Ymin = np.floor(np.min(Ymes)/10)*10 fw, fh = 6, 6 fig = mpl.figure.Figure(figsize=(fw, fh)) canvas = FigureCanvas(fig) # ---- Create Axes leftMargin = 1. / fw rightMargin = 0.25 / fw bottomMargin = 0.8 / fh topMargin = 0.25 / fh x0 = leftMargin y0 = bottomMargin w0 = 1 - (leftMargin + rightMargin) h0 = 1 - (bottomMargin + topMargin) ax0 = fig.add_axes([x0, y0, w0, h0]) ax0.set_axisbelow(True) ax0.grid(axis='both', color='0.', linestyle='--', linewidth=0.5, dashes=[0.5, 3]) # ---- Plot # Estimation Error hscat, = ax0.plot(Ymes, Ypre, '.', mec='k', mfc='k', ms=12, alpha=0.35) hscat.set_rasterized(True) # 1:1 Line dl = 12 # dashes length ds = 6 # spacing between dashes dew = 0.5 # dashes edge width dlw = 1.5 # dashes line width # Plot a white contour line ax0.plot([Ymin, Ymax], [Ymin, Ymax], '-w', lw=dlw + 2 * dew, alpha=1) # Plot a black dashed line hbl, = ax0.plot([Ymin, Ymax], [Ymin, Ymax], 'k', lw=dlw, dashes=[dl, ds], dash_capstyle='butt') # ---- Text # Calculate Statistics RMSE = (np.mean((Ypre - Ymes) ** 2)) ** 0.5 MAE = np.mean(np.abs(Ypre - Ymes)) ME = np.mean(Ypre - Ymes) r = np.corrcoef(Ypre, Ymes)[1, 0] print('RMSE=%0.1f ; MAE=%0.1f ; ME=%0.2f ; r=%0.3f' % (RMSE, MAE, ME, r)) Emax = np.min(Ypre - Ymes) Emin = np.max(Ypre - Ymes) print('Emax=%0.1f ; Emin=%0.1f' % (Emax, Emin)) # Generate and Plot Labels if varName in ['Max Temp (deg C)', 'Mean Temp (deg C)', 'Min Temp (deg C)']: units = u'°C' elif varName in ['Total Precip (mm)']: units = 'mm' else: units = '' tcontent = [u'RMSE = %0.1f %s' % (RMSE, units), u'MAE = %0.1f %s' % (MAE, units), u'ME = %0.2f %s' % (ME, units), u'r = %0.3f' % (r)] tcontent = list(reversed(tcontent)) for i in range(len(tcontent)): dx, dy = -10 / 72., 10 * (i+1) / 72. padding = mpl.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) transform = ax0.transAxes + padding ax0.text(0, 0, tcontent[i], ha='left', va='bottom', fontsize=16, transform=transform) # ---- Get Labels Win. Extents hext, vext = np.array([]), np.array([]) renderer = canvas.get_renderer() for text in ax0.texts: bbox = text.get_window_extent(renderer) bbox = bbox.transformed(ax0.transAxes.inverted()) hext = np.append(hext, bbox.width) vext = np.append(vext, bbox.height) # ---- Position Labels in Axes x0 = 1 - np.max(hext) y0 = 0 for i, text in enumerate(ax0.texts): text.set_position((x0, y0)) y0 += vext[i] # ----- Labels ax0.xaxis.set_ticks_position('bottom') ax0.yaxis.set_ticks_position('left') ax0.tick_params(axis='both', direction='out', labelsize=14) if varName == 'Max Temp (deg C)': if language == 'French': var = u'Températures maximales journalières %s (°C)' else: var = u'%s Daily Max Temperature (°C)' elif varName == 'Mean Temp (deg C)': if language == 'French': var = u'Températures moyennes journalières %s (°C)' else: var = u'%s Daily Mean Temperature (°C)' elif varName == 'Min Temp (deg C)': if language == 'French': var = u'Températures minimales journalières %s (°C)' else: var = u'%s Daily Min Temperature (°C)' elif varName == 'Total Precip (mm)': if language == 'French': var = u'Précipitations totales journalières %s (mm)' else: var = '%s Daily Total Precipitation (mm)' else: var = '' if language == 'French': ax0.set_xlabel(var % u'mesurées', fontsize=16, labelpad=15) ax0.set_ylabel(var % u'prédites', fontsize=16, labelpad=15) else: ax0.set_xlabel(var % 'Measured', fontsize=16, labelpad=15) ax0.set_ylabel(var % 'Predicted', fontsize=16, labelpad=15) # ---- Axis ax0.axis([Ymin, Ymax, Ymin, Ymax]) # ---- Legend if language == 'French': lglabels = ['Données journalières', '1:1'] else: lglabels = ['Daily weather data', '1:1'] ax0.legend([hscat, hbl], lglabels, loc='upper left', numpoints=1, frameon=False, fontsize=16) # ---- Draw fig.savefig(fname, dpi=300) return canvas
img = cam.getImage().scale(0.3) rgb = img.getNumpyCv2() hist = cv2.calcHist([rgb], [0, 1, 2], None, [bins, bins, bins], [0, 256, 0, 256, 0, 256]) hist = hist / np.max(hist) # render everything [ ax.plot([x], [y], [z], '.', markersize=max(hist[x, y, z] * 100, 6), color=color) for x, y, z, color in idxs if (hist[x][y][z] > 0) ] #[ ax.plot([x],[y],[z],'.',color=color) for x,y,z,color in idxs if(hist[x][y][z]>0) ] ax.set_xlim3d(0, bins - 1) ax.set_ylim3d(0, bins - 1) ax.set_zlim3d(0, bins - 1) azim = (azim + 0.5) % 360 ax.view_init(elev=35, azim=azim) ########### convert matplotlib to SimpleCV image canvas.draw() renderer = canvas.get_renderer() raw_data = renderer.tostring_rgb() size = canvas.get_width_height() surf = pg.image.fromstring(raw_data, size, "RGB") figure = Image(surf) ############ All done figure = figure.floodFill((0, 0), tolerance=5, color=Color.WHITE) result = figure.blit(img, pos=(20, 20)) result.save(disp) fig.clf()
while disp.isNotDone(): ax = fig.gca(projection='3d') ax.set_xlabel('BLUE', color=(0,0,1) ) ax.set_ylabel('GREEN',color=(0,1,0)) ax.set_zlabel('RED',color=(1,0,0)) # Get the color histogram img = cam.getImage().scale(0.3) rgb = img.getNumpyCv2() hist = cv2.calcHist([rgb],[0,1,2],None,[bins,bins,bins],[0,256,0,256,0,256]) hist = hist/np.max(hist) # render everything [ ax.plot([x],[y],[z],'.',markersize=max(hist[x,y,z]*100,6),color=color) for x,y,z,color in idxs if(hist[x][y][z]>0) ] #[ ax.plot([x],[y],[z],'.',color=color) for x,y,z,color in idxs if(hist[x][y][z]>0) ] ax.set_xlim3d(0, bins-1) ax.set_ylim3d(0, bins-1) ax.set_zlim3d(0, bins-1) azim = (azim+0.5)%360 ax.view_init(elev=35, azim=azim) ########### convert matplotlib to SimpleCV image canvas.draw() renderer = canvas.get_renderer() raw_data = renderer.tostring_rgb() size = canvas.get_width_height() surf = pg.image.fromstring(raw_data, size, "RGB") figure = Image(surf) ############ All done figure = figure.floodFill((0,0), tolerance=5,color=Color.WHITE) result = figure.blit(img, pos=(20,20)) result.save(disp) fig.clf()
class RightFrame: """ This class is for creating right frame widgets which are used to draw graphics on canvas as well as embedding matplotlib figures in the tkinter. Kush Raina 2018_06_03 """ def __init__(self, root, master, debug_print_flag=False): self.root = root self.master = master self.debug_print_flag = debug_print_flag width_px = root.winfo_screenwidth() height_px = root.winfo_screenheight() width_mm = root.winfo_screenmmwidth() height_mm = root.winfo_screenmmheight() # 2.54 cm = in width_in = width_mm / 25.4 height_in = height_mm / 25.4 width_dpi = width_px / width_in height_dpi = height_px / height_in if self.debug_print_flag: print('Width: %i px, Height: %i px' % (width_px, height_px)) print('Width: %i mm, Height: %i mm' % (width_mm, height_mm)) print('Width: %f in, Height: %f in' % (width_in, height_in)) print('Width: %f dpi, Height: %f dpi' % (width_dpi, height_dpi)) # self.canvas = self.master.canvas ######################################################################### # Set up the plotting frame and controls frame ######################################################################### master.rowconfigure(0, weight=10, minsize=200) master.columnconfigure(0, weight=1) master.rowconfigure(1, weight=1, minsize=20) self.right_frame = tk.Frame(self.master, borderwidth=10, relief='sunken') self.right_frame.grid(row=0, column=0, columnspan=1, sticky=tk.N + tk.E + tk.S + tk.W) self.matplotlib_width_pixel = self.right_frame.winfo_width() self.matplotlib_height_pixel = self.right_frame.winfo_height() # set up the frame which contains controls such as sliders and buttons self.controls_frame = tk.Frame(self.master) self.controls_frame.grid(row=1, column=0, sticky=tk.N + tk.E + tk.S + tk.W) self.controls_frame.rowconfigure(1, weight=1, minsize=20) self.draw_button = tk.Button(self.controls_frame, text="Draw", fg="red", width=16, command=self.graphics_draw_callback) self.plot_2d_button = tk.Button( self.controls_frame, text="Plot 2D", fg="red", width=16, command=self.matplotlib_plot_2d_callback) self.plot_3d_button = tk.Button( self.controls_frame, text="Plot 3D", fg="red", width=16, command=self.matplotlib_plot_3d_callback) self.draw_button.grid(row=0, column=0) self.plot_2d_button.grid(row=0, column=1) self.plot_3d_button.grid(row=0, column=2) self.right_frame.update() self.canvas = tk.Canvas(self.right_frame, relief='ridge', width=self.right_frame.winfo_width() - 110, height=self.right_frame.winfo_height()) if self.debug_print_flag: print("Right frame width, right frame height : ", self.right_frame.winfo_width(), self.right_frame.winfo_height()) self.canvas.rowconfigure(0, weight=1) self.canvas.columnconfigure(0, weight=1) self.canvas.grid(row=0, column=0, sticky=tk.N + tk.E + tk.S + tk.W) self.canvas.bind("<ButtonPress-1>", self.left_mouse_click_callback) self.canvas.bind("<ButtonRelease-1>", self.left_mouse_release_callback) self.canvas.bind("<B1-Motion>", self.left_mouse_down_motion_callback) self.canvas.bind("<ButtonPress-3>", self.right_mouse_click_callback) self.canvas.bind("<ButtonRelease-3>", self.right_mouse_release_callback) self.canvas.bind("<B3-Motion>", self.right_mouse_down_motion_callback) self.canvas.bind("<Key>", self.key_pressed_callback) self.canvas.bind("<Up>", self.up_arrow_pressed_callback) self.canvas.bind("<Down>", self.down_arrow_pressed_callback) self.canvas.bind("<Right>", self.right_arrow_pressed_callback) self.canvas.bind("<Left>", self.left_arrow_pressed_callback) self.canvas.bind("<Shift-Up>", self.shift_up_arrow_pressed_callback) self.canvas.bind("<Shift-Down>", self.shift_down_arrow_pressed_callback) self.canvas.bind("<Shift-Right>", self.shift_right_arrow_pressed_callback) self.canvas.bind("<Shift-Left>", self.shift_left_arrow_pressed_callback) self.canvas.bind("f", self.f_key_pressed_callback) self.canvas.bind("b", self.b_key_pressed_callback) # Create a figure for 2d plotting self.matplotlib_2d_fig = mpl.figure.Figure() # self.matplotlib_2d_fig.set_size_inches(4,2) self.matplotlib_2d_fig.set_size_inches( (self.right_frame.winfo_width() / width_dpi) - 0.5, self.right_frame.winfo_height() / height_dpi) self.matplotlib_2d_ax = self.matplotlib_2d_fig.add_axes( [.1, .1, .7, .7]) if self.debug_print_flag: print("Matplotlib figsize in inches: ", (self.right_frame.winfo_width() / width_dpi) - 0.5, self.right_frame.winfo_height() / height_dpi) self.matplotlib_2d_fig_x, self.matplotlib_2d_fig_y = 0, 0 self.matplotlib_2d_fig_loc = (self.matplotlib_2d_fig_x, self.matplotlib_2d_fig_y) # fig = plt.figure() # ax = fig.gca(projection='3d') # Create a figure for 3d plotting self.matplotlib_3d_fig = mpl.figure.Figure() self.matplotlib_3d_figure_canvas_agg = FigureCanvasAgg( self.matplotlib_3d_fig) # self.matplotlib_2d_fig.set_size_inches(4,2) self.matplotlib_3d_fig.set_size_inches( (self.right_frame.winfo_width() / width_dpi) - 0.5, self.right_frame.winfo_height() / height_dpi) self.matplotlib_3d_ax = self.matplotlib_3d_fig.add_axes( [.1, .1, .6, .6], projection='3d') self.matplotlib_3d_fig_x, self.matplotlib_3d_fig_y = 0, 0 self.matplotlib_3d_fig_loc = (self.matplotlib_3d_fig_x, self.matplotlib_3d_fig_y) 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 display_matplotlib_3d_figure_on_tk_canvas(self): self.matplotlib_3d_ax.clear() r = np.linspace(0, 6, 100) temp = np.random.rand() theta = np.linspace(-temp * np.pi, temp * np.pi, 40) r, theta = np.meshgrid(r, theta) X = r * np.sin(theta) Y = r * np.cos(theta) Z = np.sin(np.sqrt(X**2 + Y**2)) surf = self.matplotlib_3d_ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="coolwarm", linewidth=0, antialiased=False) # surf = self.matplotlib_3d_ax.plot_surface(X, Y, Z, rcount=1, ccount=1, cmap='bwr', edgecolor='none'); self.matplotlib_3d_ax.set_xlim(-6, 6) self.matplotlib_3d_ax.set_ylim(-6, 6) self.matplotlib_3d_ax.set_zlim(-1.01, 1.01) self.matplotlib_3d_ax.zaxis.set_major_locator(LinearLocator(10)) self.matplotlib_3d_ax.zaxis.set_major_formatter( FormatStrFormatter('%.02f')) # Place the matplotlib figure on canvas and display it self.matplotlib_3d_figure_canvas_agg.draw() self.matplotlib_3d_figure_x, self.matplotlib_3d_figure_y, self.matplotlib_3d_figure_w, \ self.matplotlib_3d_figure_h = self.matplotlib_2d_fig.bbox.bounds self.matplotlib_3d_figure_w, self.matplotlib_3d_figure_h = int( self.matplotlib_3d_figure_w), int(self.matplotlib_3d_figure_h) if self.debug_print_flag: print("Matplotlib 3d figure x, y, w, h: ", self.matplotlib_3d_figure_x, self.matplotlib_3d_figure_y, self.matplotlib_3d_figure_w, self.matplotlib_3d_figure_h) self.photo = tk.PhotoImage(master=self.canvas, width=self.matplotlib_3d_figure_w, height=self.matplotlib_3d_figure_h) # Position: convert from top-left anchor to center anchor self.canvas.create_image( self.matplotlib_3d_fig_loc[0] + self.matplotlib_3d_figure_w / 2, self.matplotlib_3d_fig_loc[1] + self.matplotlib_3d_figure_h / 2, image=self.photo) tkagg.blit( self.photo, self.matplotlib_3d_figure_canvas_agg.get_renderer()._renderer, colormode=2) self.matplotlib_3d_fig_w, self.matplotlib_3d_fig_h = self.photo.width( ), self.photo.height() def key_pressed_callback(self, event): self.root.status_bar.set('%s', 'Key pressed') def up_arrow_pressed_callback(self, event): self.root.status_bar.set('%s', "Up arrow was pressed") def down_arrow_pressed_callback(self, event): self.root.status_bar.set('%s', "Down arrow was pressed") def right_arrow_pressed_callback(self, event): self.root.status_bar.set('%s', "Right arrow was pressed") def left_arrow_pressed_callback(self, event): self.root.status_bar.set('%s', "Left arrow was pressed") def shift_up_arrow_pressed_callback(self, event): self.root.status_bar.set('%s', "Shift up arrow was pressed") def shift_down_arrow_pressed_callback(self, event): self.root.status_bar.set('%s', "Shift down arrow was pressed") def shift_right_arrow_pressed_callback(self, event): self.root.status_bar.set('%s', "Shift right arrow was pressed") def shift_left_arrow_pressed_callback(self, event): self.root.status_bar.set('%s', "Shift left arrow was pressed") def f_key_pressed_callback(self, event): self.root.status_bar.set('%s', "f key was pressed") def b_key_pressed_callback(self, event): self.root.status_bar.set('%s', "b key was pressed") def left_mouse_click_callback(self, event): self.root.status_bar.set( '%s', 'Left mouse button was clicked. ' + 'x=' + str(event.x) + ' y=' + str(event.y)) self.x = event.x self.y = event.y self.canvas.focus_set() def left_mouse_release_callback(self, event): self.root.status_bar.set( '%s', 'Left mouse button was released. ' + 'x=' + str(event.x) + ' y=' + str(event.y)) self.x = None self.y = None def left_mouse_down_motion_callback(self, event): self.root.status_bar.set( '%s', 'Left mouse down motion. ' + 'x=' + str(event.x) + ' y=' + str(event.y)) self.x = event.x self.y = event.y def right_mouse_click_callback(self, event): self.root.status_bar.set( '%s', 'Right mouse down motion. ' + 'x=' + str(event.x) + ' y=' + str(event.y)) self.x = event.x self.y = event.y def right_mouse_release_callback(self, event): self.root.status_bar.set( '%s', 'Right mouse button was released. ' + 'x=' + str(event.x) + ' y=' + str(event.y)) self.x = None self.y = None def right_mouse_down_motion_callback(self, event): self.root.status_bar.set( '%s', 'Right mouse down motion. ' + 'x=' + str(event.x) + ' y=' + str(event.y)) self.x = event.x self.y = event.y def left_mouse_click_callback(self, event): self.root.status_bar.set( '%s', 'Left mouse button was clicked. ' + 'x=' + str(event.x) + ' y=' + str(event.y)) self.x = event.x self.y = event.y # self.focus_set() def frame_resized_callback(self, event): print("frame resize callback") def create_graphic_objects(self): self.canvas.delete("all") r = np.random.rand() self.drawing_objects = [] for scale in np.linspace(.1, 0.8, 20): self.drawing_objects.append( self.canvas.create_oval( int(scale * int(self.canvas.cget("width"))), int(r * int(self.canvas.cget("height"))), int((1 - scale) * int(self.canvas.cget("width"))), int((1 - scale) * int(self.canvas.cget("height"))))) def redisplay(self, event): self.create_graphic_objects() def matplotlib_plot_2d_callback(self): self.display_matplotlib_figure_on_tk_canvas() self.root.status_bar.set( '%s', "called matplotlib_plot_2d_callback callback!") def matplotlib_plot_3d_callback(self): self.display_matplotlib_3d_figure_on_tk_canvas() self.root.status_bar.set( '%s', "called matplotlib_plot_3d_callback callback!") def graphics_draw_callback(self): self.create_graphic_objects() self.root.status_bar.set('%s', "called the draw callback!")