class CanvasPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() self.sizer = wx.BoxSizer(wx.VERTICAL) #self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.sizer.Add(self.canvas, 1, wx.EXPAND | wx.ALL) # Best to allow the toolbar to resize! self.sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(self.sizer) self.Fit() def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def draw(self): t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) self.axes.plot(t, s) def OnPaint(self, event): self.canvas.draw()
class PlotPanel(wx.Panel): """This example is from something I found on the matplotlib webpage. They combined an embedded mpl plot with the wxPython xrc approach. They basically create a wx.Panel placeholder in the xrc file. See data_vis_gui.py for an example of using this class. Your really don't need anything other than the __init__ method. After that, just grab :py:attr:`self.fig` and use the matplotlib methods of the figure instance (the object-oriented API, not pylab).""" def __init__(self, parent, fig_size=(8, 6)): wx.Panel.__init__(self, parent, -1) self.fig = Figure(fig_size, 100) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) # Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.Fit() def init_plot_data(self): """This just creates the starting graph.""" a = self.fig.add_subplot(111) t = np.arange(0, 1, 0.01) y = np.sin(2 * np.pi * t) self.lines = a.plot(t, y) self.ax = a self.toolbar.update() # Not sure why this is needed - ADS def change_plot(self): """This is just a method to show I can update the plot from a program. It doesn't really do anything else useful. It serves as an example of clearing the axis, plotting something, and refreshing the graph.""" self.ax.clear() t = np.arange(0, 1, 0.01) y2 = np.cos(2 * np.pi * t) self.ax.plot(t, y2) self.canvas.draw() def GetToolBar(self): """This is from the example; I don't know what it does.""" # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def onEraseBackground(self, evt): """I don't know what this does either (based on the comment below, I guess it prevents flicker).""" # this is supposed to prevent redraw flicker on some X servers... pass
class PlotPanel(wxPanel): def __init__(self, parent): wxPanel.__init__(self, parent, -1) self.fig = Figure((5, 4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # Now put all into a sizer sizer = wxBoxSizer(wxVERTICAL) # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wxLEFT | wxTOP | wxGROW) # Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, wxGROW) self.SetSizer(sizer) self.Fit() def init_plot_data(self): a = self.fig.add_subplot(111) x = numerix.arange(120.0) * 2 * numerix.pi / 60.0 y = numerix.arange(100.0) * 2 * numerix.pi / 50.0 self.x, self.y = meshgrid(x, y) z = numerix.sin(self.x) + numerix.cos(self.y) self.im = a.imshow(z, cmap=cm.jet) #, interpolation='nearest') zmax = numerix.max(numerix.max(z)) - ERR_TOL ymax_i, xmax_i = numerix.nonzero(numerix.greater_equal(z, zmax)) if self.im.origin == 'upper': ymax_i = z.shape[0] - ymax_i self.lines = a.plot(xmax_i, ymax_i, 'ko') self.toolbar.update() # Not sure why this is needed - ADS def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def OnWhiz(self, evt): self.x += numerix.pi / 15 self.y += numerix.pi / 20 z = numerix.sin(self.x) + numerix.cos(self.y) self.im.set_array(z) zmax = numerix.max(numerix.max(z)) - ERR_TOL ymax_i, xmax_i = numerix.nonzero(numerix.greater_equal(z, zmax)) if self.im.origin == 'upper': ymax_i = z.shape[0] - ymax_i self.lines[0].set_data(xmax_i, ymax_i) self.canvas.draw() def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass
class PlotFigure(wxFrame): def __init__(self): wxFrame.__init__(self, None, -1, "Test embedded wxFigure") self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() # On Windows, default frame size behaviour is incorrect # you don't need this under Linux tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(wxSize(fw, th)) # Create a figure manager to manage things # Now put all into a sizer sizer = wxBoxSizer(wxVERTICAL) # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wxLEFT|wxTOP|wxGROW) # Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, wxGROW) self.SetSizer(sizer) self.Fit() EVT_TIMER(self, TIMER_ID, self.onTimer) def init_plot_data(self): # jdh you can add a subplot directly from the fig rather than # the fig manager a = self.fig.add_subplot(111) self.x = numerix.arange(120.0)*2*numerix.pi/120.0 self.x.resize((100,120)) self.y = numerix.arange(100.0)*2*numerix.pi/100.0 self.y.resize((120,100)) self.y = numerix.transpose(self.y) z = numerix.sin(self.x) + numerix.cos(self.y) self.im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest') def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def onTimer(self, evt): self.x += numerix.pi/15 self.y += numerix.pi/20 z = numerix.sin(self.x) + numerix.cos(self.y) self.im.set_array(z) self.canvas.draw() #self.canvas.gui_repaint() # jdh wxagg_draw calls this already def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass
class MatplotPanel(wx.Panel): def __init__(self, parent,config): panel1 = wx.Panel.__init__(self, parent) self.figure = Figure() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar self.toolbar.EnableTool(1,False) self.toolbar.Realize() # self.toolbar.set_active([0,1]) self.toolbar.update() sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) # Best to allow the toolbar to resize! #sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.Fit() self.Refresh(eraseBackground=True)
class PlotPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure((5, 4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar self.toolbar.Realize() # self.toolbar.set_active([0,1]) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) # Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.Fit() def init_plot_data(self): a = self.fig.add_subplot(111)
class Panel_Plotting_Helper(wx.Panel): def __init__(self, parent): w, h = parent.GetSize() wx.Panel.__init__(self, parent=parent, size=(w, 0.7 * h), style=wx.SUNKEN_BORDER) self.parent = parent self.legends = [] self.legendpos = [0.5, 1] self.fig = Figure( figsize=(12, 6), dpi=90) # create a figure size 8x6 inches, 80 dots per inches self.splts = [] self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar # additional toolbar status_txt = wx.StaticText(self.toolbar, label=' Status on hover: ', pos=(230, 7), \ size=(100, 17)) self.status = wx.TextCtrl(self.toolbar, pos=(330,4), size=(300, 22), \ style=wx.TE_READONLY) self.toolbar.Realize() self.figw, self.figh = self.fig.get_window_extent( ).width, self.fig.get_window_extent().height sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.toolbar, 0, wx.GROW) sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(sizer) self.box_width_fraction = 1.0 self.box_height_fraction = 0.9 self.lines = [] self.lined = dict() self.draggableList = ['Text', 'Legend'] # print(self.toolbar.GetBackgroundColour()) self.fig.canvas.mpl_connect('resize_event', self.squeeze_legend) self.fig.canvas.mpl_connect('pick_event', self.on_pick) self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion) self.fig.canvas.mpl_connect('figure_leave_event', self.on_leave) def plot_J(self, J, theta, format, r, count): index = count % 3 + 3 self.splts[index].plot(np.arange(len(J)), J, color=format['color'], linewidth=format['linewidth'], linestyle=format['linestyle'], label=format['label'], picker=True) self.splts[index].set_xlabel("Number of Iteration", fontsize=FONT_SIZE) self.splts[index].set_ylabel("Cost value", fontsize=FONT_SIZE) self.set_ticks(self.splts[index], np.arange(len(J)), J) comment = r + ': [\n' for t in theta: comment += ' ' + str(t) + '\n' comment += ']' props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) annotate = self.splts[index].annotate(comment, xy=(len(J)-1, J[len(J)-1]), xytext=(len(J)/2, (J[0]+J[len(J)-1])/2), \ arrowprops=dict(facecolor='black', shrink=0.05), bbox=props, fontsize=FONT_SIZE, picker=True) annotate.draggable(True) def plot_data_gradient_descent(self, X, y, format): print("Plotting data ...") for i in range(int(round(len(self.splts) / 2))): self.plot_data(self.splts[i], X, y, format) self.update_canvas() def plot_data_normal_equation(self, X, y, format): print("Plotting data ...") for i in range(int(round((len(self.splts) + 1) / 2))): self.plot_data(self.splts[i], X, y, format) self.update_canvas() def plot_data(self, splt, X, y, format): line, = splt.plot(X, y, 'ro', color=format['color'], label=format['label'], picker=True) self.set_ticks(splt, X, y) self.lines.append(line) splt.set_xlabel("X1", fontsize=FONT_SIZE) splt.set_ylabel("Y", fontsize=FONT_SIZE) def set_ticks(self, splt, X, y): xticks = self.make_ticks(X) yticks = self.make_ticks(y) splt.set_xticks(xticks) splt.set_yticks(yticks) for tick in splt.get_xticklabels(): tick.set_rotation(45) tick.set_fontsize(FONT_SIZE) for tick in splt.get_yticklabels(): tick.set_rotation(45) tick.set_fontsize(FONT_SIZE) def plot_all_gradient_descent(self, object): print( "Plotting Linear-Regression (Gradient Descent) and J-Convergence ..." ) count = 0 for r in object: c = self.random_color() self.splts[count].plot(object[r]['data']['x'], object[r]['data']['y'], color=c, linestyle="-", label="Linear Regression (alpha=" + r + ")", picker=True) self.set_ticks(self.splts[count], object[r]['data']['x'], object[r]['data']['y']) self.plot_J( object[r]['J_history'], object[r]['theta'], { "color": c, "linewidth": 5, "linestyle": "-", "label": "Convergence of J" }, r, count) count += 1 self.show_legend() self.update_canvas() def plot_all_normal_equation(self, object): print("Plotting Linear-Regression (Normal Equation) ...") count = 0 for r in object: c = self.random_color() line, = self.splts[count].plot( object[r]['data']['x'], object[r]['data']['y'], color=c, linestyle="-", label="Linear Regression (Normal Equation)", picker=True) self.lines.append(line) self.set_ticks(self.splts[count], object[r]['data']['x'], object[r]['data']['y']) comment = 'Theta: [\n' for t in object[r]['theta']: comment += ' ' + str(t[0]) + '\n' comment += ']' # place a text box in upper left in axes coords props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) annotate = self.splts[count].annotate(comment, xy=(min(object[r]['data']['x']), max(object[r]['data']['y'])), \ xytext=(min(object[r]['data']['x']), max(object[r]['data']['y'])), bbox=props, fontsize=FONT_SIZE, picker=True) annotate.draggable(True) count += 1 self.show_legend() self.update_canvas() def show_legend(self): self.legends = [] for i in range(len(self.splts)): splt = self.splts[i] # Shrink current axis by 20% box = splt.get_position() splt.set_position([box.x0, box.y0, box.width * self.box_width_fraction, \ box.height * self.box_height_fraction]) # Now add the legend with some customizations. legend = splt.legend(loc='upper center', ncol=1, fancybox=True, shadow=True) legend.set_bbox_to_anchor((self.legendpos[0], \ self.legendpos[1] + legend.get_window_extent().height/self.figh + 0.25)) legend.figure.canvas.mpl_connect('pick_event', self.on_pick) legend.draggable(True) # lined = dict() # for legline, origline in zip(legend.get_lines(), self.lines): # legline.set_picker(5) # 5 pts tolerance # self.lined[legline] = origline self.legends.append(legend) if legend: # The frame is matplotlib.patches.Rectangle instance surrounding the legend. frame = legend.get_frame() frame.set_facecolor('0.90') # Set the fontsize for label in legend.get_texts(): label.set_fontsize(FONT_SIZE) for label in legend.get_lines(): label.set_linewidth(0.75) # the legend line width else: pass def make_ticks(self, data): minn = np.min(data) maxx = np.max(data) return np.arange(minn, maxx, int((maxx - minn) / 3)) def squeeze_legend(self, evt): new_height = self.fig.get_window_extent().height self.box_height_fraction = new_height / self.figh self.figh = new_height new_width = self.fig.get_window_extent().width self.box_width_fraction = new_width / self.figw self.figw = new_width self.show_legend() self.update_canvas() def on_pick(self, evt): if isinstance(evt.artist, Text): # box_points = evt.artist.get_position() global TEXT_DRAGGABLE TEXT_DRAGGABLE = not TEXT_DRAGGABLE evt.artist.draggable(TEXT_DRAGGABLE) elif isinstance(evt.artist, Line2D): # box_points = evt.artist.get_clip_box() pass elif isinstance(evt.artist, Legend): # box_points = evt.artist.get_clip_box() global LEGEND_DRAGGABLE LEGEND_DRAGGABLE = not LEGEND_DRAGGABLE evt.artist.draggable(LEGEND_DRAGGABLE) else: print(evt.artist) pass # print("You've clicked on a bar with coords:\n %r, %r" % (box_points , evt.artist)) self.update_canvas() def on_motion(self, mouseevt): w, h = self.canvas.GetSize() if mouseevt.x in range(0, int(w + 1)) and mouseevt.y in range( 0, int(h + 1)): self.status.SetValue('Click on %r for dragging On/Off' % self.draggableList) else: pass def on_leave(self, mouseevt): self.status.SetValue('') def make_figure(self, type): self.fig.clf() if type == 'gd': gs = GridSpec(2, 3) gs.update(hspace=0.7, wspace=0.8) self.splts = [ self.fig.add_subplot(gs[int(i / 3), int(i % 3)]) for i in range(2 * 3) ] # grid nxn elif type == 'ne': gs = GridSpec(1, 1) gs.update(hspace=0.7, wspace=0.8) self.splts = [ self.fig.add_subplot(gs[int(i / 3), int(i % 3)]) for i in range(1 * 1) ] # grid nxn else: pass def random_color(self): rgbl = [0, random.random(), random.random()] return tuple(rgbl) def update_canvas(self): self.fig.canvas.draw() self.canvas.Refresh() self.toolbar.update()
class HistPlotPanel(wx.Panel): def __init__(self, parent, id, size=(4, 3), dpi=75, **kwds): wx.Panel.__init__(self, parent, id) import wxmpl.wxmpl as wxmpl self.canvas = wxmpl.PlotPanel(self, -1, size=size, dpi=dpi) self.figure = self.canvas.figure self.figure.add_subplot(111) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() # On Windows, default frame size behaviour is incorrect # you don't need this under Linux tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(wx.Size(fw, th)) # Create a figure manager to manage things self.figmgr = FigureManager(self.canvas, 1, self) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) # add a spacer between figure and toolbar sizer.AddSpacer((10, 10)) # Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.sizer = sizer self.SetAutoLayout(1) sizer.Fit(self) #FigureCanvasWxAgg.__init__(self, parent, id, Figure(size, dpi) ) from histogram.plotter import HistogramMplPlotter as HMP self.plotter = HMP(self.figure) shelf = self.getShelf() shelf.update({"plot": Plot(self)}) return def GetToolBar(self): return self.toolbar def getShelf(self): return self.GetParent().getShelf() def showHist(self, histIdentifier): hist = self.getShelf().get(histIdentifier) if hist is None: print("Unable to retrieve histogram %s" % histIdentifier) return self.currentHist = hist self.showCurrentHist() return def showCurrentHist(self): hist = self.currentHist self.plotter.plot(hist) self.Refresh() return pass # end of HistPlotPanel