def __init__(self, *k, **kw): super(MagcalPanel, self).__init__(*k, **kw) facecolor = self.GetBackgroundColour().GetAsString(wx.C2S_HTML_SYNTAX) fig = plt.figure(facecolor=facecolor, figsize=(1,1)) self._canvas = FigureCanvas(self, wx.ID_ANY, fig) self._canvas.SetMinSize((300,300)) self._id_text = wx.StaticText(self, wx.ID_ANY) self._status_text = wx.StaticText(self, wx.ID_ANY) self._completion_pct_text = wx.StaticText(self, wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self._id_text) sizer.Add(self._status_text) sizer.Add(self._completion_pct_text) sizer.Add(self._canvas, proportion=1, flag=wx.EXPAND) self.SetSizer(sizer) ax = fig.add_subplot(111, axis_bgcolor=facecolor, projection='3d') self.configure_plot(ax)
def __init__(self, parent): wx.Panel.__init__(self,parent=parent, id=-1) # 分割子图实现代码 self.figure = Figure() gs = gridspec.GridSpec(2, 1, left=0.05, bottom=0.1, right=0.95, top=0.95, wspace=None, hspace=0.1, height_ratios=[2, 1]) self.graph_trade = self.figure.add_subplot(gs[0, :]) self.graph_profit = self.figure.add_subplot(gs[1, :]) self.FigureCanvas = FigureCanvas(self, -1, self.figure) # figure加到FigureCanvas self.NavigationToolbar = NavigationToolbar(self.FigureCanvas) self.StaticText = wx.StaticText(self, -1, label=u'微信公众号《元宵大师带你用Python量化交易》') self.SubBoxSizer = wx.BoxSizer(wx.HORIZONTAL) self.SubBoxSizer.Add(self.NavigationToolbar, proportion=0, border=2, flag=wx.ALL | wx.EXPAND) self.SubBoxSizer.Add(self.StaticText, proportion=0, border=2, flag=wx.ALL | wx.EXPAND) self.TopBoxSizer = wx.BoxSizer(wx.VERTICAL) self.TopBoxSizer.Add(self.FigureCanvas, proportion=1, border=2, flag=wx.ALL|wx.EXPAND) self.TopBoxSizer.Add(self.SubBoxSizer, proportion=0, border=2, flag=wx.ALL | wx.EXPAND) self.SetSizer(self.TopBoxSizer) self.Fit()
def create_speed_plot(self): self.speed_panel = wx.Panel(self) self.dpi = 100 self.fig = Figure((3.8, 1.95), dpi=self.dpi, facecolor='w') self.fig.subplots_adjust(top=0.95, right=0.97, bottom=0.07) self.speedplot = self.fig.add_subplot(111) self.speedplot.set_axis_bgcolor('black') #self.speedplot.set_title('AVALON Speed History', size=10) self.speedplot.set_ylabel('[knots]', size=8) pylab.setp(self.speedplot.get_xticklabels(), fontsize=8) pylab.setp(self.speedplot.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.speedplot.plot( self.speeddata, linewidth=1, color=(1, 1, 0), )[0] self.speed_canvas = FigureCanvas(self.speed_panel, -1, self.fig)
def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(800, 400)) # Matplotlib Figure self.fig = Figure((0, 0), 100) # bind the Figure to the backend specific canvas self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig) # add a subplot self.ax = self.fig.add_subplot(111) # limit the X and Y axes dimensions self.ax.set_ylim([0, 100]) self.ax.set_xlim([0, POINTS]) self.ax.set_autoscale_on(False) self.ax.set_xticks([]) # we want a tick every 10 point on Y (101 is to have 10 self.ax.set_yticks(range(0, 101, 10)) # disable autoscale, since we don't want the Axes to ad # draw a grid (it will be only for Y) self.ax.grid(True) # generates first "empty" plots self.user = [None] * POINTS self.l_user,=self.ax.plot(range(POINTS),self.user,label='User %') # add the legend self.ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10)) # force a draw on the canvas() # trick to show the grid and the legend self.canvas.draw() # save the clean background - everything but the line # is drawn and saved in the pixel buffer background self.bg = self.canvas.copy_from_bbox(self.ax.bbox) # bind events coming from timer with id = TIMER_ID # to the onTimer callback function wx.EVT_TIMER(self, TIMER_ID, self.onTimer)
def __init__(self,parent): wx.Panel.__init__(self, parent, -1) self.Conf = BridgeConfClass() # serve per prendere le dimensioni del box dove plottare exo self.dpi = 45 self.dim_pan = parent.GetSize() #self.figure = Figure(figsize=(self.dim_pan[0]*1.0/self.dpi,(self.dim_pan[1])*1.0/self.dpi), dpi=self.dpi) self.figure = Figure(dpi=self.dpi) #sysTextColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENU) #colore sfondo come finestra #col_norm = (sysTextColour[0]*1.0/255, sysTextColour[1]*1.0/255, sysTextColour[2]*1.0/255) #self.figure.patch.set_facecolor(col_norm) # Canvas self.canvas = FigureCanvas(parent, -1, self.figure) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.canvas, 1, wx.ALL | wx.EXPAND) self.ax = self.figure.add_subplot(1, 1, 1) self.ax.axis('equal') self.ax.set_ylim(1.5*(self.Conf.l1+self.Conf.l2+self.Conf.l3), (self.Conf.l1+self.Conf.l2+self.Conf.l3)) self.ax.set_xlim(1.5*(self.Conf.l1+self.Conf.l2+self.Conf.l3), (self.Conf.l1+self.Conf.l2+self.Conf.l3)) " Set virtual exo " marker_style = dict(linestyle='-', color=[0.2, 0.2, 0.2], markersize=20) self.line = self.ax.plot([], [], marker='o', **marker_style)[0] self.ax.set_xticklabels([]) self.ax.set_yticklabels([]) parent.SetSizer(sizer1) parent.Fit()
def __init__(self, ): wx.Frame.__init__(self, None, -1, 'Activity Map', size=(750, 750)) self.SetBackgroundColour(wx.NamedColor("BLACK")) self.figure = Figure(figsize=(5, 5)) self.axes = self.figure.add_subplot(111) duder = array(rangevecReorg) duder.shape = 80, 80 self.axes.imshow(duder, origin='upper', cmap=cm.hot, extent=(0, 80, 0, 80)) self.axes.set_xlabel(str(FileString[0])) self.axes.set_ylabel('y') self.figure_canvas = FigureCanvas(self, -1, self.figure) # Note that event is a MplEvent self.figure_canvas.mpl_connect('motion_notify_event', self.UpdateStatusBar) self.figure_canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.figure_canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.Fit() self.statusBar = wx.StatusBar(self, -1) self.statusBar.SetFieldsCount(1) self.SetStatusBar(self.statusBar) self.toolbar = NavigationToolbar2Wx(self.figure_canvas) self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.toolbar.Show()
def __init__(self, parent, user_data): """ Initialize everything here """ super(Analysis_Panel, self).__init__(parent, style=wx.BORDER_DOUBLE) self.SetBackgroundColour(wx.Colour("White")) self.x_vals, self.y_vals = None, None # self.speech_x_vals, self.speech_y_vals = None, None self.user_data = user_data self.figure = Figure(figsize=(1, 1)) # DPI = self.figure.get_dpi() # print("DPI:", DPI) # DefaultSize = self.figure.get_size_inches() # print("Default size in Inches", DefaultSize) # print("Which should result in a %i x %i Image" % (DPI * DefaultSize[0], DPI * DefaultSize[1])) self.axes, self.axes_intensity, self.axes_pitch = self.figure.subplots( 3, sharex='col') self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.figure.subplots_adjust(top=0.98, bottom=0.15) #adjusted correctly self.sld = wx.Slider(self, value=0, minValue=0, maxValue=100, size=(545, -1), style=wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_SELRANGE) self.sizer.Add(self.sld, 0, wx.LEFT, 77) self.sizer.Add(self.canvas, 1, wx.EXPAND) self.SetSizer(self.sizer) self.sizer.Fit(self) # self.InitUI() pub.subscribe(self.changePitch, "PITCH_CHANGE") pub.subscribe(self.changeLevel, "LEVEL_CHANGE") pub.subscribe(self.changeSlider, "SLIDER_CHANGE") pub.subscribe(self.playAnimation, "PLAY")
def __init__(self, parent): wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) self.date = [] today = datetime.date.today() self.date.append(today) self.date = str(self.date[0]) self.gridIndex = 0 self.estTimes = [0] self.estTemps = [0] self.dataTimes = [0] self.dataTemps = [0] self.initPlot() self.canvas = FigureCanvas(self, -1, self.fig) self.dataGrid = mygrid.MyGrid(self) sizer.Add(self.canvas) sizer.Add(self.dataGrid) self.SetSizer(sizer) self.canvas.draw()
def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.parent = parent from matplotlib.backends.backend_wx import _load_bitmap import pathlib self.figure = mpl.figure.Figure(dpi=None, figsize=(2, 2)) self.canvas = FigureCanvas(self, -1, self.figure) self.axes = self.figure.add_subplot(111) """disini untuk menentukan nilai sumbu x dan sumbu y""" self.x = [1, 2, 3, 4, 5, 6] self.y = [1, 2, 3, 4, 5, 6] self.axes.plot(self.x, self.y) self.toolbar = NavigationToolbar(self.canvas) self.pathimage = pathlib.Path.cwd() / "resources/images/binadata.png" self.newpathimage = pathlib.Path.cwd() / "resources/images/bila.png" self.ON_CUSTOM = wx.NewIdRef() self.image1 = wx.Image(str(self.pathimage)) self.re_image3 = self.image1.Rescale(20, 20) self.re_image3.SaveFile(self.newpathimage.as_posix()) self.newpathimage print(self.re_image3) self.toolbar.AddSimpleTool(self.ON_CUSTOM, _load_bitmap(self.newpathimage),\ 'Pan to the left', 'Pan graph to the left') self.toolbar.Realize() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(sizer)
def __init__(self): """ Initialize the frame """ wx.Frame.__init__(self, None, -1, 'Apodization Viewer') self.SetBackgroundColour(wx.NamedColor("WHITE")) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.params = ParameterPanel(self) self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() # layout fsizer = wx.BoxSizer(wx.VERTICAL) fsizer.Add(self.canvas, 0, wx.EXPAND) fsizer.Add(self.toolbar, 0, wx.EXPAND) self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.params, 0, wx.EXPAND) self.sizer.Add(fsizer, 0, wx.EXPAND) self.SetSizer(self.sizer) self.Fit()
def __init__(self, parent, fgs, port, aui_notebook, manager, app): super().__init__(port, "PlotControl(%s)" % port.name) self.port = port self.aui_notebook = aui_notebook self.manager = manager self.app = app self.parent = parent self.fig = Figure((5, 0.8), 75) self.canvas = FigureCanvas(parent, -1, self.fig) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.canvas, 7, wx.ALIGN_CENTRE | wx.LEFT) fgs.Add(sizer, 0, wx.TOP | wx.EXPAND) # handlers self.canvas.mpl_connect("axes_enter_event", self.enter_axes) self.canvas.mpl_connect("axes_leave_event", self.leave_axes) self.canvas.mpl_connect("button_press_event", self.OnDrag) self.canvas.mpl_connect("button_release_event", self.OnDrag) self.evaluate()
def __init__(self, parent): wx.Panel.__init__(self, parent=parent, id=-1) self.Figure = matplotlib.figure.Figure(figsize=(4, 3)) self.axes = self.Figure.add_axes([0.1, 0.1, 0.8, 0.8]) self.FigureCanvas = FigureCanvas(self, -1, self.Figure) #继承鼠标移动显示鼠标处坐标的事件 self.FigureCanvas.mpl_connect('motion_notify_event', self.MPLOnMouseMove) self.NavigationToolbar = NavigationToolbar(self.FigureCanvas) self.StaticText = wx.StaticText(self, -1, label='Show Help String') self.SubBoxSizer = wx.BoxSizer(wx.HORIZONTAL) self.SubBoxSizer.Add(self.NavigationToolbar, proportion=0, border=2, flag=wx.ALL | wx.EXPAND) self.SubBoxSizer.Add(self.StaticText, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND) self.TopBoxSizer = wx.BoxSizer(wx.VERTICAL) self.TopBoxSizer.Add(self.SubBoxSizer, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND) self.TopBoxSizer.Add(self.FigureCanvas, proportion=-10, border=2, flag=wx.ALL | wx.EXPAND) self.SetSizer(self.TopBoxSizer)
def update(self): """ Updates the image with the current slider index """ #set image size: imgW = self.gui_width * .007 #was 12 inches (perhaps add dpi!) imgH = self.gui_height * .007 #was 7 inches self.img_size = (imgW, imgH) # width, height in inches. self.vid.set(1, self.currFrame) self.fig1, (self.ax1f1) = plt.subplots(figsize=self.img_size, facecolor="None") ret, frame = self.vid.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) im_axis = self.ax1f1.imshow(frame) self.ax1f1.set_title( str( str(self.currFrame) + "/" + str(self.numberFrames) + " " + self.filename)) self.ax1f1.axis("off") # self.ax1f1.set_title(str(str(self.currFrame)+"/"+str(self.numberFrames) +" "+ self.filename)) self.canvas = FigureCanvas(self, -1, self.fig1)
def __init__(self, parent, size=(200, 250)): super().__init__(parent) self.figure = Figure(figsize=(5, 4)) self.axes = self.figure.add_subplot(111) self.parent = parent self.canvas = FigureCanvas(self, -1, self.figure) self.canvas.Position = (50, 105) self.axes.set_title('Id Vg') self.axes.set_xlabel("Vg (Volt)") self.axes.set_ylabel("Id (Amps)") self.axes.plot(Window.x, Window.y, ".k") self.RS = RectangleSelector(self.axes, self.line_select_callback, drawtype='box', useblit=True, button=[1, 3], minspanx=5, minspany=5, spancoords='pixels', interactive=True, rectprops=dict(facecolor='None', edgecolor='blue', alpha=0.5, fill=False)) self.canvas.draw()
def __init__(self, gridfile, riverfile): wx.Frame.__init__(self, None, -1, 'PyEditRiver', size=(1024, 800)) self.maintoolbar = MainToolBar(self) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND) self.SetSizer(self.sizer) self.Fit() self.log = wx.TextCtrl(wx.Panel(self), wx.ID_ANY, size=(400, 300), style=wx.TE_MULTILINE | wx.TE_READONLY | wx.VSCROLL) self.add_toolbar() # comment this out for no toolbar if gridfile: self.maintoolbar.showGrid(gridfile) if riverfile: self.maintoolbar.showRivers(riverfile)
def __init__(self, fp): wx.Frame.__init__(self, None) self.bmp = None self.cap = cv2.VideoCapture(fp) ret, frame = self.cap.read() h, w, c = frame.shape print(w, h, c) property_id = int(cv2.CAP_PROP_FRAME_COUNT) length = int(cv2.VideoCapture.get(self.cap, property_id)) print(length) videopPanel = VideoPanel(self, (w, h)) self.videotimer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnUpdateVidoe, self.videotimer) self.videotimer.Start(1) self.graph = Figure() # matplotlib figure plottPanel = FigureCanvas(self, -1, self.graph) self.ax = self.graph.add_subplot(111) y = frame.mean(axis=0).mean(axis=1) self.line, = self.ax.plot(y) self.ax.set_xlim([0, length]) self.ax.set_ylim([0, 255]) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(videopPanel) sizer.Add(plottPanel) self.SetSizer(sizer) self.Fit() self.Show(True)
def __init__(self, parent: wx.Window, fig: Figure, ax: Axes, id: int = wx.ID_ANY, pos: wx.Point = wx.DefaultPosition, size: wx.Size = wx.DefaultSize, style: int = 0, name: str = wx.PanelNameStr): wx.Panel.__init__(self, parent, id, pos, size, style | wx.TAB_TRAVERSAL, name) self.fig = fig self.ax = ax self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig) self._do_layout() self.toolbar = NavigationToolbar(self.canvas) self.toolbar.Hide() self.Bind(wx.EVT_SIZE, self.on_size_change, self) self.Bind(wx.EVT_MAXIMIZE, self.on_size_change)
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.figure.tight_layout() self.chart_toolbar = MyCustomToolbar(self.canvas) tw, th = self.chart_toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.chart_toolbar.SetSize(wx.Size(fw, th)) self.chart_toolbar.Realize() self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 0, wx.LEFT | wx.TOP | wx.GROW) self.sizer.Add(self.chart_toolbar, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.Fit() Cursor(self.axes, useblit=True, color='red', linewidth=1)
def __init__(self, parent, params=None): wx.Panel.__init__(self, parent) self.pparams = params self.prime_sizer = wx.BoxSizer(wx.VERTICAL) self.prime_figure = Figure() self.prime_figure.patch.set_alpha(0) plt.rc('font', family='sans-serif', size=10) plt.rc('mathtext', default='regular') # Create nested GridSpec gsp = gridspec.GridSpec(2, 2, height_ratios=[2, 3]) self.cc_axes = self.prime_figure.add_subplot(gsp[0]) self.comp_axes = self.prime_figure.add_subplot(gsp[1]) self.mult_axes = self.comp_axes.twinx() self.rej_table = self.prime_figure.add_subplot(gsp[2]) gsub = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=gsp[3], hspace=0) self.bcc_axes = self.prime_figure.add_subplot(gsub[0]) self.bcomp_axes = self.prime_figure.add_subplot(gsub[1], sharex=self.bcc_axes) self.bmult_axes = self.prime_figure.add_subplot(gsub[2], sharex=self.bcc_axes) self.draw_axes() # Set layout, create canvas, add to sizer self.prime_figure.set_tight_layout(True) self.canvas = FigureCanvas(self, -1, self.prime_figure) self.prime_sizer.Add(self.canvas, proportion=1, flag=wx.EXPAND) # Initialize main sizer self.SetSizer(self.prime_sizer)
def draw(self): data = np.loadtxt(self.fileName, delimiter='\t', skiprows=2) data = data[:, 0:2] x = data[:, 0] y = data[:, 1] self.figure = Figure(figsize=(5, 4), frameon=True, constrained_layout=False) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.canvas.Position = (50, 105) self.axes.set_title('Id Vg') self.axes.set_xlabel("Vg (Volt)") self.axes.set_ylabel("Id (Amps)") self.axes.plot( x, y, ".", ) self.RS = RectangleSelector(self.axes, self.line_select_callback, drawtype='box', useblit=True, button=[1, 3], minspanx=5, minspany=5, spancoords='pixels', interactive=True, rectprops=dict(facecolor='None', edgecolor='red', alpha=0.5, fill=False))
def __init__(self, parent): wx.Panel.__init__(self, parent, style=wx.BORDER_SUNKEN) self.sliceFigure = Figure(frameon=True, figsize=(2, 3)) self.sliceFigure.set_facecolor('.82') self.sliceCanvas = FigureCanvas(self, -1, self.sliceFigure) self.sliceCanvas.SetAutoLayout(False) self.box = Toolbar(self.sliceCanvas) self.box.Hide() self.box.zoom() self.fm = FigureManagerBase(self.sliceCanvas, 1) _pylab_helpers.Gcf.set_active(self.fm) self.sliceAxis = self.sliceFigure.add_axes([0.1, 0.2, 0.8, 0.7]) sliceSizer = wx.BoxSizer(wx.VERTICAL) sliceSizer.Add(self.sliceCanvas, 1, wx.EXPAND | wx.RIGHT | wx.LEFT, border=1) self.SetSizer(sliceSizer) return
def __init__(self, parent, spectrum, location, settings): self.filename = "" self.spectrum = spectrum self.location = location self.settings = settings self.directory = settings.dirExport self.colourMap = settings.colourMap self.colourHeat = settings.colourMap self.canvas = None self.extent = None self.xyz = None self.plotAxes = False self.plotMesh = True self.plotCont = True self.plotPoint = False self.plotHeat = False self.plot = None wx.Dialog.__init__(self, parent=parent, title='Export Map') colours = get_colours() freqMin = min(spectrum[min(spectrum)]) * 1000 freqMax = max(spectrum[min(spectrum)]) * 1000 bw = freqMax - freqMin self.figure = matplotlib.figure.Figure(facecolor='white') self.figure.set_size_inches((6, 6)) self.canvas = FigureCanvas(self, -1, self.figure) self.axes = self.figure.add_subplot(111) if matplotlib.__version__ >= '1.2': self.figure.tight_layout() self.figure.subplots_adjust(left=0, right=1, top=1, bottom=0) textPlot = wx.StaticText(self, label='Plot') self.checkAxes = wx.CheckBox(self, label='Axes') self.checkAxes.SetValue(self.plotAxes) self.Bind(wx.EVT_CHECKBOX, self.__on_axes, self.checkAxes) self.checkCont = wx.CheckBox(self, label='Contour lines') self.checkCont.SetValue(self.plotCont) self.Bind(wx.EVT_CHECKBOX, self.__on_cont, self.checkCont) self.checkPoint = wx.CheckBox(self, label='Locations') self.checkPoint.SetValue(self.plotPoint) self.Bind(wx.EVT_CHECKBOX, self.__on_point, self.checkPoint) sizerPlotCheck = wx.BoxSizer(wx.HORIZONTAL) sizerPlotCheck.Add(self.checkAxes, flag=wx.ALL, border=5) sizerPlotCheck.Add(self.checkCont, flag=wx.ALL, border=5) sizerPlotCheck.Add(self.checkPoint, flag=wx.ALL, border=5) sizerPlot = wx.BoxSizer(wx.VERTICAL) sizerPlot.Add(textPlot, flag=wx.ALL, border=5) sizerPlot.Add(sizerPlotCheck, flag=wx.ALL, border=5) textMesh = wx.StaticText(self, label='Mesh') self.checkMesh = wx.CheckBox(self, label='On') self.checkMesh.SetToolTip('Signal level mesh') self.checkMesh.SetValue(self.plotMesh) self.Bind(wx.EVT_CHECKBOX, self.__on_mesh, self.checkMesh) self.choiceMapMesh = wx.Choice(self, choices=colours) self.choiceMapMesh.SetSelection(colours.index(self.colourMap)) self.Bind(wx.EVT_CHOICE, self.__on_colour_mesh, self.choiceMapMesh) self.barMesh = PanelColourBar(self, self.colourMap) sizerMapMesh = wx.BoxSizer(wx.HORIZONTAL) sizerMapMesh.Add(self.choiceMapMesh, flag=wx.ALL, border=5) sizerMapMesh.Add(self.barMesh, flag=wx.ALL, border=5) sizerMesh = wx.BoxSizer(wx.VERTICAL) sizerMesh.Add(textMesh, flag=wx.ALL, border=5) sizerMesh.Add(self.checkMesh, flag=wx.ALL, border=5) sizerMesh.Add(sizerMapMesh, flag=wx.ALL, border=5) colours = get_colours() textHeat = wx.StaticText(self, label='Heat map') self.checkHeat = wx.CheckBox(self, label='On') self.checkHeat.SetToolTip('GPS location heatmap') self.checkHeat.SetValue(self.plotHeat) self.Bind(wx.EVT_CHECKBOX, self.__on_heat, self.checkHeat) self.choiceMapHeat = wx.Choice(self, choices=colours) self.choiceMapHeat.SetSelection(colours.index(self.colourHeat)) self.Bind(wx.EVT_CHOICE, self.__on_colour_heat, self.choiceMapHeat) self.barHeat = PanelColourBar(self, self.colourHeat) sizerMapHeat = wx.BoxSizer(wx.HORIZONTAL) sizerMapHeat.Add(self.choiceMapHeat, flag=wx.ALL, border=5) sizerMapHeat.Add(self.barHeat, flag=wx.ALL, border=5) sizerHeat = wx.BoxSizer(wx.VERTICAL) sizerHeat.Add(textHeat, flag=wx.ALL, border=5) sizerHeat.Add(self.checkHeat, flag=wx.ALL, border=5) sizerHeat.Add(sizerMapHeat, flag=wx.ALL, border=5) textRange = wx.StaticText(self, label='Range') textCentre = wx.StaticText(self, label='Centre') self.spinCentre = wx.SpinCtrl(self) self.spinCentre.SetToolTip('Centre frequency (kHz)') self.spinCentre.SetRange(freqMin, freqMax) self.spinCentre.SetValue(freqMin + bw / 2) sizerCentre = wx.BoxSizer(wx.HORIZONTAL) sizerCentre.Add(textCentre, flag=wx.ALL, border=5) sizerCentre.Add(self.spinCentre, flag=wx.ALL, border=5) textBw = wx.StaticText(self, label='Bandwidth') self.spinBw = wx.SpinCtrl(self) self.spinBw.SetToolTip('Bandwidth (kHz)') self.spinBw.SetRange(1, bw) self.spinBw.SetValue(bw / 10) sizerBw = wx.BoxSizer(wx.HORIZONTAL) sizerBw.Add(textBw, flag=wx.ALL, border=5) sizerBw.Add(self.spinBw, flag=wx.ALL, border=5) buttonUpdate = wx.Button(self, label='Update') self.Bind(wx.EVT_BUTTON, self.__on_update, buttonUpdate) sizerRange = wx.BoxSizer(wx.VERTICAL) sizerRange.Add(textRange, flag=wx.ALL, border=5) sizerRange.Add(sizerCentre, flag=wx.ALL, border=5) sizerRange.Add(sizerBw, flag=wx.ALL, border=5) sizerRange.Add(buttonUpdate, flag=wx.ALL, border=5) textOutput = wx.StaticText(self, label='Output') self.textRes = wx.StaticText(self) buttonRes = wx.Button(self, label='Change...') buttonRes.SetToolTip('Change output resolution') self.Bind(wx.EVT_BUTTON, self.__on_imageres, buttonRes) sizerRes = wx.BoxSizer(wx.HORIZONTAL) sizerRes.Add(self.textRes, flag=wx.ALL, border=5) sizerRes.Add(buttonRes, flag=wx.ALL, border=5) sizerOutput = wx.BoxSizer(wx.VERTICAL) sizerOutput.Add(textOutput, flag=wx.ALL, border=5) sizerOutput.Add(sizerRes, flag=wx.ALL, border=5) self.__show_image_res() font = textPlot.GetFont() fontSize = font.GetPointSize() font.SetPointSize(fontSize + 4) textPlot.SetFont(font) textMesh.SetFont(font) textHeat.SetFont(font) textRange.SetFont(font) textOutput.SetFont(font) sizerButtons = wx.StdDialogButtonSizer() buttonOk = wx.Button(self, wx.ID_OK) buttonCancel = wx.Button(self, wx.ID_CANCEL) sizerButtons.AddButton(buttonOk) sizerButtons.AddButton(buttonCancel) sizerButtons.Realize() self.Bind(wx.EVT_BUTTON, self.__on_ok, buttonOk) self.__setup_plot() sizerGrid = wx.GridBagSizer(5, 5) sizerGrid.Add(self.canvas, pos=(0, 0), span=(5, 6), flag=wx.EXPAND | wx.ALL, border=5) sizerGrid.Add(sizerPlot, pos=(0, 7), flag=wx.EXPAND | wx.ALL, border=5) sizerGrid.Add(sizerMesh, pos=(1, 7), flag=wx.EXPAND | wx.ALL, border=5) sizerGrid.Add(sizerHeat, pos=(2, 7), flag=wx.EXPAND | wx.ALL, border=5) sizerGrid.Add(sizerRange, pos=(3, 7), flag=wx.EXPAND | wx.ALL, border=5) sizerGrid.Add(sizerOutput, pos=(4, 7), flag=wx.EXPAND | wx.ALL, border=5) sizerGrid.Add(sizerButtons, pos=(5, 7), span=(1, 2), flag=wx.ALIGN_RIGHT | wx.ALL, border=5) self.SetSizerAndFit(sizerGrid) self.__draw_plot()
def browseDir(self, event): """ Show the DirDialog and ask the user to change the directory where machine labels are stored """ from skimage import io dlg = wx.DirDialog(self, "Choose the directory where your extracted frames are saved:",os.getcwd(), style = wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK: self.dir = dlg.GetPath() self.Button1.Enable(False) self.Button2.Enable(True) self.Button5.Enable(True) else: dlg.Destroy() self.Close(True) dlg.Destroy() with open(str(self.config_file), 'r') as ymlfile: self.cfg = yaml.load(ymlfile) self.scorer = self.cfg['scorer'] self.bodyparts = self.cfg['bodyparts'] self.videos = self.cfg['video_sets'].keys() self.markerSize = self.cfg['dotsize'] self.colormap = plt.get_cmap(self.cfg['colormap']) self.project_path=self.cfg['project_path'] self.index = glob.glob(os.path.join(self.dir,'*.png')) self.relativeimagenames=self.index ##[n.split(self.project_path+'/')[1] for n in self.index] self.fig1, (self.ax1f1) = plt.subplots(figsize=(12, 7.8),facecolor = "None") self.iter = 0 self.buttonCounter = [] im = io.imread(self.index[self.iter]) im_axis = self.ax1f1.imshow(im, self.colormap) img_name = Path(self.index[self.iter]).name # self.index[self.iter].split('/')[-1] self.ax1f1.set_title(str(str(self.iter)+"/"+str(len(self.index)-1) +" "+ img_name )) self.canvas = FigureCanvas(self.top_split,-1,self.fig1) #checks for unique bodyparts if len(self.bodyparts)!=len(set(self.bodyparts)): print("Error! bodyparts must have unique labels!Please choose unique bodyparts in config.yaml file and try again. Quiting for now!") self.Destroy() if self.new_labels == True: self.oldDF = pd.read_hdf(os.path.join(self.dir,'CollectedData_'+self.scorer+'.h5'),'df_with_missing') oldBodyParts = self.oldDF.columns.get_level_values(1) _, idx = np.unique(oldBodyParts, return_index=True) oldbodyparts2plot = list(oldBodyParts[np.sort(idx)]) self.bodyparts = list(set(self.bodyparts) - set(oldbodyparts2plot)) self.rdb = wx.RadioBox(self.top_split, id=1, label="Select a body part to annotate",pos=(1250, 65), choices=self.bodyparts, majorDimension =1,style=wx.RA_SPECIFY_COLS,validator=wx.DefaultValidator, name=wx.RadioBoxNameStr) self.option = self.rdb.Bind(wx.EVT_RADIOBOX,self.onRDB) cbar = self.fig1.colorbar(im_axis, ax = self.ax1f1) cbar.set_ticks(range(12,np.max(im),int(np.floor(np.max(im)/len(self.bodyparts)-1)))) cbar.set_ticklabels(self.bodyparts) else: self.addLabel.Enable(False) cbar = self.fig1.colorbar(im_axis, ax = self.ax1f1) cbar.set_ticks(range(12,np.max(im),int(np.floor(np.max(im)/len(self.bodyparts)-1)))) cbar.set_ticklabels(self.bodyparts) self.rdb = wx.RadioBox(self.top_split, id=1, label="Select a body part to annotate",pos=(1250, 65), choices=self.bodyparts, majorDimension =1,style=wx.RA_SPECIFY_COLS,validator=wx.DefaultValidator, name=wx.RadioBoxNameStr) self.option = self.rdb.Bind(wx.EVT_RADIOBOX,self.onRDB) self.cidClick = self.canvas.mpl_connect('button_press_event', self.onClick) self.flag = 0 self.num = [] self.counter = [] self.presentCoords = [] self.colorparams = list(range(0,len(self.bodyparts)+1)) a = np.empty((len(self.index),2,)) a[:] = np.nan for bodypart in self.bodyparts: index = pd.MultiIndex.from_product([[self.scorer], [bodypart], ['x', 'y']],names=['scorer', 'bodyparts', 'coords']) #frame = pd.DataFrame(a, columns = index, index = self.index) frame = pd.DataFrame(a, columns = index, index = self.relativeimagenames) self.dataFrame = pd.concat([self.dataFrame, frame],axis=1) if self.file == 0: self.checkBox = wx.CheckBox(self.top_split, label = 'Adjust marker size.',pos = (500, 855)) self.checkBox.Bind(wx.EVT_CHECKBOX,self.onChecked) self.slider = wx.Slider(self.top_split, -1, 5, 0, 20,size=(200, -1), pos=(500, 780),style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS ) self.slider.Bind(wx.EVT_SLIDER, self.OnSliderScroll) self.slider.Enable(False)
def download_usgs(self, event): station_id = self.m_textCtrl1.GetValue() df, names = read_usgs_flow([station_id]) pd.to_numeric(df.iloc[:, 1]).plot(ax=self.axes) print(df.head()) self.canvas = FigureCanvas(self.m_panel1, -1, self.m_panel1.figure)
def __init__(self, parent, spectrum, settings): self.spectrum = spectrum self.settings = settings self.sweeps = None self.isExporting = False wx.Dialog.__init__(self, parent=parent, title='Export Plot Sequence') self.queue = Queue() self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__on_timer, self.timer) self.timer.Start(self.POLL) self.figure = Figure(facecolor='white') self.canvas = FigureCanvas(self, -1, self.figure) self.plot = Plotter(self.queue, self.figure, settings) textPlot = wx.StaticText(self, label='Plot') self.checkAxes = wx.CheckBox(self, label='Axes') self.checkAxes.SetValue(True) self.Bind(wx.EVT_CHECKBOX, self.__on_axes, self.checkAxes) self.checkGrid = wx.CheckBox(self, label='Grid') self.checkGrid.SetValue(True) self.Bind(wx.EVT_CHECKBOX, self.__on_grid, self.checkGrid) self.checkBar = wx.CheckBox(self, label='Bar') self.checkBar.SetValue(True) self.Bind(wx.EVT_CHECKBOX, self.__on_bar, self.checkBar) sizerCheck = wx.BoxSizer(wx.HORIZONTAL) sizerCheck.Add(self.checkAxes, flag=wx.ALL, border=5) sizerCheck.Add(self.checkGrid, flag=wx.ALL, border=5) sizerCheck.Add(self.checkBar, flag=wx.ALL, border=5) textRange = wx.StaticText(self, label='Range') self.sweepTimeStamps = sorted( [timeStamp for timeStamp in spectrum.keys()]) sweepChoices = [ format_time(timeStamp, True) for timeStamp in self.sweepTimeStamps ] textStart = wx.StaticText(self, label="Start") self.choiceStart = wx.Choice(self, choices=sweepChoices) self.choiceStart.SetSelection(0) self.Bind(wx.EVT_CHOICE, self.__on_choice, self.choiceStart) textEnd = wx.StaticText(self, label="End") self.choiceEnd = wx.Choice(self, choices=sweepChoices) self.choiceEnd.SetSelection(len(self.sweepTimeStamps) - 1) self.Bind(wx.EVT_CHOICE, self.__on_choice, self.choiceEnd) textSweeps = wx.StaticText(self, label='Sweeps') self.textSweeps = wx.StaticText(self, label="") textOutput = wx.StaticText(self, label='Output') self.textSize = wx.StaticText(self) buttonSize = wx.Button(self, label='Change...') buttonSize.SetToolTip('Change exported image size') self.Bind(wx.EVT_BUTTON, self.__on_imagesize, buttonSize) self.__show_image_size() buttonBrowse = wx.Button(self, label='Browse...') self.Bind(wx.EVT_BUTTON, self.__on_browse, buttonBrowse) self.editDir = wx.TextCtrl(self) self.editDir.SetValue(settings.dirExport) font = textPlot.GetFont() fontSize = font.GetPointSize() font.SetPointSize(fontSize + 4) textPlot.SetFont(font) textRange.SetFont(font) textOutput.SetFont(font) sizerButtons = wx.StdDialogButtonSizer() buttonOk = wx.Button(self, wx.ID_OK) buttonCancel = wx.Button(self, wx.ID_CANCEL) sizerButtons.AddButton(buttonOk) sizerButtons.AddButton(buttonCancel) sizerButtons.Realize() self.Bind(wx.EVT_BUTTON, self.__on_ok, buttonOk) sizerGrid = wx.GridBagSizer(5, 5) sizerGrid.Add(self.canvas, pos=(0, 0), span=(10, 6), flag=wx.EXPAND | wx.ALL, border=5) sizerGrid.Add(textPlot, pos=(0, 7), flag=wx.TOP | wx.BOTTOM, border=5) sizerGrid.Add(sizerCheck, pos=(1, 7), span=(1, 2), flag=wx.ALL, border=5) sizerGrid.Add(textRange, pos=(2, 7), flag=wx.TOP | wx.BOTTOM, border=5) sizerGrid.Add(textStart, pos=(3, 7), flag=wx.ALIGN_CENTRE_VERTICAL | wx.ALL, border=5) sizerGrid.Add(self.choiceStart, pos=(3, 8), flag=wx.ALL, border=5) sizerGrid.Add(textEnd, pos=(4, 7), flag=wx.ALIGN_CENTRE_VERTICAL | wx.ALL, border=5) sizerGrid.Add(self.choiceEnd, pos=(4, 8), flag=wx.ALL, border=5) sizerGrid.Add(textSweeps, pos=(5, 7), flag=wx.ALIGN_CENTRE_VERTICAL | wx.ALL, border=5) sizerGrid.Add(self.textSweeps, pos=(5, 8), flag=wx.ALIGN_CENTRE_VERTICAL | wx.ALL, border=5) sizerGrid.Add(textOutput, pos=(6, 7), flag=wx.TOP | wx.BOTTOM, border=5) sizerGrid.Add(self.textSize, pos=(7, 7), flag=wx.ALIGN_CENTRE_VERTICAL | wx.ALL, border=5) sizerGrid.Add(buttonSize, pos=(7, 8), flag=wx.ALL, border=5) sizerGrid.Add(self.editDir, pos=(8, 7), span=(1, 2), flag=wx.ALL | wx.EXPAND, border=5) sizerGrid.Add(buttonBrowse, pos=(9, 7), flag=wx.ALL, border=5) sizerGrid.Add(sizerButtons, pos=(10, 7), span=(1, 2), flag=wx.ALIGN_RIGHT | wx.ALL, border=5) self.SetSizerAndFit(sizerGrid) self.__draw_plot()
def replaceHist(self, list1, list2): self.figure = matplotlib.figure.Figure() self.axes = self.figure.add_subplot(111) self.axes.hist(list1, list2) self.canvas = FigureCanvas(self, -1, self.figure)
def _makeUI(self): """Make the window and all widgets""" min_plot_w = min_plot_h = 400 min_tree_w = 160 menubar = wx.MenuBar() menu = wx.Menu() self.SetMenuBar(menubar) self.Bind(wx.EVT_MENU, self._on_select_file, menu.Append(wx.ID_FILE, 'Open &file(s)', 'Open a file')) self.Bind(wx.EVT_MENU, self._on_select_folder, menu.Append(wx.ID_OPEN, 'Open fol&der', 'Open a folder')) menu.AppendSeparator() self.Bind(wx.EVT_MENU, lambda evt: self.Close(), menu.Append(wx.ID_EXIT, '&Quit', 'Quit application')) menubar.Append(menu, '&File') self.Sizer = wx.BoxSizer(wx.HORIZONTAL) splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE, size=(min_plot_w + 400, min_plot_h)) splitter.SetMinimumPaneSize(1) splitter.SetSashGravity(0.0) figure = Figure() self.axis = figure.add_axes((0.1, 0.1, .8, .8)) self.axis.xaxis_date() self.axis.xaxis.set_major_formatter( matplotlib.dates.DateFormatter('%H:%M')) self.axis.xaxis.set_major_locator(matplotlib.ticker.LinearLocator()) self.axis_r = self.axis.twinx() # Need to put navbar in same panel as the canvas - putting it # in an outer layer means it may not be drawn correctly or at all. fig_panel = wx.Panel(splitter, size=(min_plot_w, min_plot_h)) fig_panel.Sizer = wx.BoxSizer(wx.VERTICAL) self.canvas = FigureCanvas(fig_panel, -1, figure) nav_bar = NavigationToolbar(self.canvas) fig_panel.Sizer.Add(self.canvas, -1, wx.EXPAND) fig_panel.Sizer.Add(nav_bar, 0, wx.LEFT) self.tree = wx.TreeCtrl(splitter, -1, wx.DefaultPosition, size=(min_tree_w, -1), style=wx.TR_MULTIPLE | wx.TR_HAS_BUTTONS | wx.TR_LINES_AT_ROOT | wx.TR_HIDE_ROOT) self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.on_tree_sel_changed) self.tree.Bind(wx.EVT_CONTEXT_MENU, self.on_tree_right_click) splitter.SplitVertically(self.tree, fig_panel) splitter.SashPosition = min_tree_w self.Sizer.Add(splitter, 1, flag=wx.EXPAND) # Create am imagelist so the tree also acts as a legend. # The 0th element is a bitmap with the tree's background colour. iml = wx.ImageList(*BMP_SIZE, mask=False, initialCount=0) iml.Add( wx.Bitmap.FromRGBA(BMP_SIZE[0], BMP_SIZE[1], *self.tree.GetBackgroundColour())) for hex in sorted(C_TO_I, key=C_TO_I.get): iml.Add(make_bitmap(hex, 'L')) iml.Add(make_bitmap(hex, 'R')) self.tree.AssignImageList(iml) self.Fit()
def __init__(self, argv): wx.Frame.__init__(self, None, -1, 'UCR 2015 Learning Results', size=(550, 350)) parser = argparse.ArgumentParser( description= "utility to graph success levels for learning on the UCR Dataset") parser.add_argument( '-d', '--directory', help='Directory where the learning results are stored', required=False) parser.add_argument('files', metavar='FILE', nargs='*') self.args = vars(parser.parse_args(argv[1:])) if self.args['directory'] != None and len(self.args['files']) != 0: print "Ignoring files after the directory argument" elif self.args['directory'] == None and len(self.args['files']) == 0: parser.print_help() sys.exit() if self.args['directory'] != None: if os.path.isdir(self.args['directory']): self.files = subprocess.check_output([ "find", self.args['directory'], "-name", "*Learning.json*" ]) self.files = [f for f in self.files.split("\n") if f != ''] else: parser.print_help() sys.exit() else: self.files = self.args['files'] def learning_type(text): fields = text.split('-') t = fields[-1].split('.')[0][:-len('Learning')] try: if t == 'PersistenceKernel' or t == 'ScaleSpaceSimilarity' or t == 'MultipleKernel' or t == 'AverageKernel': if 'ChaosPost' in fields: w = '-Chaos' else: w = '-' + fields[fields.index('win') + 1] else: w = '' except ValueError: w = '' return t + w self.learning_types = list(set([learning_type(f) for f in self.files])) self.learning_types.sort() datasets = list(set([f.split('/')[-2] for f in self.files])) datasets.sort() self.filedict = dict([(s, dict([(t, 0) for t in self.learning_types])) for s in datasets]) # load in the data files for f in self.files: learning_t = learning_type(f) dataset = f.split('/')[-2] learning_json = load_data(f, "learning", None, None, None) learning = Learning.fromJSONDict(learning_json) best = self.filedict[dataset][learning_t] current = learning.get_average_correct() if (isinstance(best, list) and current > sum(best)) or (not isinstance(best, list) and current > best): if learning.results[0].mkl_weights != None: self.filedict[dataset][learning_t] = [ current * w for w in learning.results[0].mkl_weights ] else: self.filedict[dataset][learning_t] = current keylen = max([len(key) for (key, val) in self.filedict.items()]) format = '%' + str(keylen) + 's %s' for (key, val) in self.filedict.items(): vals = [ ("%s %02.2f%%" % (k, v * 100.0 if not isinstance(v, list) else sum(v) * 100.0)) + ((" " + str(["%02.2f%%" % v_ for v_ in v])) if isinstance(v, list) else "") for (k, v) in val.items() ] vals.sort() print format % (key, vals) self.frame = 0 self.SetBackgroundColour(wx.NamedColour("WHITE")) self.figure = Figure() self.axes = self.figure.add_subplot(121) plot_keys = self.filedict.items()[0][1].keys() dataset_width = len(plot_keys) + 1.5 self.axes.set_xticks([(0.5 + i) * dataset_width for i in range(len(self.filedict.items()))]) self.axes.set_xticklabels( [key for (key, value) in self.filedict.items()]) self.axes.set_ylim(0.0, 1.0, auto=False) self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.title = self.figure.suptitle("UCR Learning") #self.Fit() self.background = self.axes.figure.canvas.copy_from_bbox( self.axes.bbox) self.colors = [ 'black', 'red', 'yellow', 'orange', 'blue', 'green', 'violet' ] self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_KEY_UP, self.KeyEvent) self.point_Refresh()
def __init__(self, parent, n_plots=1, axes=None, labels=None, chart_label='', sharex=False, sharey=False, transparent=True, slider=True): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib import pyplot as plt import numpy as np CtrlBase.__init__(self, parent) # Initialize the main sizer for the chart self.main_box = wx.StaticBox(self, label=chart_label) self.main_fig_sizer = wx.StaticBoxSizer(self.main_box, wx.VERTICAL) self.SetSizer(self.main_fig_sizer) # Create figure and axis array; flatten axis array to zip with other info self.track_figure, axarr = plt.subplots(n_plots, sharex=sharex) axarr_flat = [ax for sub_ax in axarr for ax in sub_ax] # Make sure the number of axes matches number of axis names / legends try: assert len(axarr_flat) == len(axes) == len(labels) except AssertionError: print 'FastPlotter Error: Match number of plots to number of ' \ 'axes and axis labels!' # Generate generic Nonetype axis object names & labels if none are provided if axes is None: axes = [None] * len(axes) if labels is None: labels = [None] * len(axes) axes_w_names = zip(axes, axarr_flat, labels) # Attach axis objects to class attributes (handling various cases) for axn in axes_w_names: ax_name = axn[0] if ax_name is None: ax_name = 'ax' + str(axes_w_names.index(axn)) ax_obj = axn[1] ax_legend = axn[2] if transparent: ax_obj.patch.set_visible(False) if ax_legend is not None: if isinstance(ax_legend, (list, tuple)): ax_obj.set_xlabel(ax_legend[0]) ax_obj.set_ylabel(ax_legend[1]) else: ax_obj.set_ylabel(ax_legend) ax_obj.set_autoscaley_on(True) setattr(self, ax_name, ax_obj) # Data-handling attributes self.xdata = [] self.ydata = [] self.x_min = 0 self.x_max = 1 self.y_max = 1 # Chart navigation attributes self.bracket_set = False self.button_hold = False self.plot_zoom = False self.chart_range = None self.selector = None self.max_lock = True self.patch_x = 0 self.patch_x_last = 1 self.patch_width = 1 self.start_edge = 0 self.end_edge = 1 # Set general figure characteristics (default tight layout) if transparent: self.track_figure.patch.set_visible(False) self.track_figure.set_tight_layout(True) self.track_canvas = FigureCanvas(self, -1, self.track_figure) # Slider bar for the plot if slider: self.plot_sb = wx.Slider(self, minValue=0, maxValue=1) self.plot_sb.Hide() self.Bind(wx.EVT_SCROLL, self.onScroll, self.plot_sb) self.main_fig_sizer.Add(self.track_canvas, 1, wx.EXPAND) self.main_fig_sizer.Add(self.plot_sb, flag=wx.EXPAND) # Plot bindings self.track_figure.canvas.mpl_connect('button_press_event', self.onPress)
def __init__(self, parent): wx.Frame.__init__(self, parent, -1, "Ring Figure - " + parent.filename, size=(550, 400)) self.parent = parent iconFile = os.path.join(parent.parent.iconspath, "diff_profiler_ico.ico") icon1 = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO) self.SetIcon(icon1) self.mpl_old = self.parent.mpl_old self.background_sub = self.parent.background_sub self.prosim = self.parent.prosim self.plot_sim = self.parent.plot_sim self.ring_patt = [] self.back_patt = [] self.dirname = self.parent.dirname self.statbar = self.CreateStatusBar( ) # A Statusbar in the bottom of the window self.statbar.SetFieldsCount(2) self.statbar.SetStatusText("None", 1) # Setting up the menu. filemenu is a local variable at this stage. figmenu = wx.Menu() # use ID_ for future easy reference - much better than "48", "404" etc # The & character indicates the short cut key self.Save_evt = figmenu.Append( wx.NewId(), "&Save Figure", "Save the figure as vestor or highres image") self.BGSub_evt = figmenu.AppendCheckItem( wx.NewId(), "&Background Subtract", "Subtract the profile fitted background from the pattern image") self.ProSim_evt = figmenu.AppendCheckItem( wx.NewId(), "&Profile Simulation", "Show the ring pattern from a profile simulation") self.PeakSim_evt = figmenu.AppendCheckItem( wx.NewId(), "Peak &Simulation", "Show a peak simulation as rings") if self.parent.background_sub: self.BGSub_evt.Check(True) else: self.BGSub_evt.Enable(False) if self.parent.prosim: self.ProSim_evt.Check(True) else: self.ProSim_evt.Enable(False) if self.parent.plot_sim: self.PeakSim_evt.Check(True) else: self.PeakSim_evt.Enable(False) # Creating the menubar. menuBar = wx.MenuBar() menuBar.Append(figmenu, "&Figure") # Adding the "patternmenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. # Note - previous line stores the whole of the menu into the current object self.SetBackgroundColour(wx.Colour("WHITE")) self.figure = Figure(figsize=(8, 8), dpi=76) self.axes = self.figure.add_axes([0, 0, 1, 1], yticks=[], xticks=[], frame_on=False) # self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND) # Capture the paint message self.Bind(wx.EVT_PAINT, self.OnPaint) self.toolbar = MyNavigationToolbar2(self, self.canvas, True) self.toolbar.Realize() tw, th = self.toolbar.GetSize() fw, fh = self.canvas.GetSize() self.toolbar.SetSize(wx.Size(fw, th)) self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) # update the axes menu on the toolbar self.toolbar.update() # Define the code to be run when a menu option is selected if self.mpl_old: self.Bind(wx.EVT_MENU, self.toolbar.save, self.Save_evt) self.Bind(wx.EVT_MENU, self.toolbar.save_figure, self.Save_evt) self.Bind(wx.EVT_MENU, self.OnBGSub, self.BGSub_evt) self.Bind(wx.EVT_MENU, self.OnProSim, self.ProSim_evt) self.Bind(wx.EVT_MENU, self.OnPeakSim, self.PeakSim_evt) self.SetSizer(self.sizer) self.Fit() self.ring_plot()
def layout_widgets(self): v = wx.BoxSizer(wx.VERTICAL) self.SetSizer(v) # Figure and figure controls self.fig = Figure((5.0, 4.0), dpi=100) self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig) self.axes = self.fig.add_subplot(111) toolbar = NavigationToolbar(self.canvas) self.plot_cursor_position_info = wx.StaticText(self, style=wx.ALIGN_RIGHT, size=(250, -1), label='') self.canvas.mpl_connect('motion_notify_event', self.mouse_position_on_plot) v.Add(self.canvas, proportion=1, flag=wx.EXPAND) h = wx.BoxSizer(wx.HORIZONTAL) h.Add(toolbar, proportion=1) h.AddSpacer(10) h.Add(self.plot_cursor_position_info, flag=wx.ALIGN_CENTER_VERTICAL) h.AddSpacer(5) v.Add(h, flag=wx.EXPAND) # Choose surface to plot h = wx.BoxSizer(wx.HORIZONTAL) v.Add(h, flag=wx.ALL | wx.EXPAND, border=4) h.Add(wx.StaticText(self, label='Surface:'), flag=wx.ALIGN_CENTER_VERTICAL) h.AddSpacer(5) self.surface_selector = wx.Choice(self) self.surface_selector.Bind(wx.EVT_CHOICE, self.reset_surfaces) h.Add(self.surface_selector, proportion=1) h.AddSpacer(5) b = wx.Button(self, label='Load') b.Bind(wx.EVT_BUTTON, self.load_surfaces) h.Add(b) # Choose timestep h = wx.BoxSizer(wx.HORIZONTAL) v.Add(h, flag=wx.ALL | wx.EXPAND, border=4) h.Add(wx.StaticText(self, label='Time step:'), flag=wx.ALIGN_CENTER_VERTICAL) h.AddSpacer(5) self.time_selector = wx.Slider(self) def lam(evt): return setattr(self, 'need_update', True) self.time_selector.Bind(wx.EVT_SLIDER, lam) h.Add(self.time_selector, proportion=1) # Customize the plot text fgs = wx.FlexGridSizer(cols=2, vgap=3, hgap=10) fgs.AddGrowableCol(1, proportion=1) v.Add(fgs, flag=wx.ALL | wx.EXPAND, border=6) # Plot title fgs.Add(wx.StaticText(self, label='Plot title:'), flag=wx.ALIGN_CENTER_VERTICAL) self.title = wx.TextCtrl(self) self.title.Bind(wx.EVT_TEXT, self.update_plot_soon) fgs.Add(self.title, flag=wx.EXPAND) # Plot xlabel / log x axis fgs.Add(wx.StaticText(self, label='Label X:'), flag=wx.ALIGN_CENTER_VERTICAL) self.xlabel = wx.TextCtrl(self) self.xlabel.Bind(wx.EVT_TEXT, self.update_plot_soon) fgs.Add(self.xlabel, flag=wx.EXPAND) # Plot ylabel fgs.Add(wx.StaticText(self, label='Label Y:'), flag=wx.ALIGN_CENTER_VERTICAL) self.ylabel = wx.TextCtrl(self) self.ylabel.Bind(wx.EVT_TEXT, self.update_plot_soon) fgs.Add(self.ylabel, flag=wx.EXPAND) # Plot ylabel fgs.Add(wx.StaticText(self, label='Aspect ratio:'), flag=wx.ALIGN_CENTER_VERTICAL) self.aspect = wx.Choice(self) self.aspect.Set(['equal', 'auto']) self.aspect.Select(0) self.aspect.Bind(wx.EVT_CHOICE, self.update_plot_soon) fgs.Add(self.aspect, flag=wx.EXPAND) v.Fit(self)
class MagcalPanel(wx.Panel): _status_markup_strings = { mavlink.MAG_CAL_NOT_STARTED: 'Not started', mavlink.MAG_CAL_WAITING_TO_START: 'Waiting to start', mavlink.MAG_CAL_RUNNING_STEP_ONE: 'Step one', mavlink.MAG_CAL_RUNNING_STEP_TWO: 'Step two', mavlink.MAG_CAL_SUCCESS: '<span color="blue">Success</span>', mavlink.MAG_CAL_FAILED: '<span color="red">Failed</span>', } _empty_color = '#7ea6ce' _filled_color = '#4680b9' def __init__(self, *k, **kw): super(MagcalPanel, self).__init__(*k, **kw) facecolor = self.GetBackgroundColour().GetAsString(wx.C2S_HTML_SYNTAX) fig = plt.figure(facecolor=facecolor, figsize=(1,1)) self._canvas = FigureCanvas(self, wx.ID_ANY, fig) self._canvas.SetMinSize((300,300)) self._id_text = wx.StaticText(self, wx.ID_ANY) self._status_text = wx.StaticText(self, wx.ID_ANY) self._completion_pct_text = wx.StaticText(self, wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self._id_text) sizer.Add(self._status_text) sizer.Add(self._completion_pct_text) sizer.Add(self._canvas, proportion=1, flag=wx.EXPAND) self.SetSizer(sizer) ax = fig.add_subplot(111, axis_bgcolor=facecolor, projection='3d') self.configure_plot(ax) def configure_plot(self, ax): extra = .5 lim = grid.radius + extra ax.set_xlim3d(-lim, lim) ax.set_ylim3d(-lim, lim) ax.set_zlim3d(-lim, lim) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.invert_zaxis() ax.invert_xaxis() ax.set_aspect('equal') self._polygons_collection = Poly3DCollection( grid.sections_triangles, edgecolors='#386694', ) ax.add_collection3d(self._polygons_collection) def update_status_from_mavlink(self, m): status_string = self._status_markup_strings.get(m.cal_status, '???') self._status_text.SetLabelMarkup( '<b>Status:</b> %s' % status_string, ) def mavlink_magcal_report(self, m): self.update_status_from_mavlink(m) self._completion_pct_text.SetLabel('') def mavlink_magcal_progress(self, m): facecolors = [] for i, mask in enumerate(m.completion_mask): for j in range(8): section = i * 8 + j if mask & 1 << j: facecolor = self._filled_color else: facecolor = self._empty_color facecolors.append(facecolor) self._polygons_collection.set_facecolors(facecolors) self._canvas.draw() self._id_text.SetLabelMarkup( '<b>Compass id:</b> %d' % m.compass_id ) self._completion_pct_text.SetLabelMarkup( '<b>Completion:</b> %d%%' % m.completion_pct ) self.update_status_from_mavlink(m) _legend_panel = None @staticmethod def legend_panel(*k, **kw): if MagcalPanel._legend_panel: return MagcalPanel._legend_panel p = MagcalPanel._legend_panel = wx.Panel(*k, **kw) sizer = wx.BoxSizer(wx.HORIZONTAL) p.SetSizer(sizer) marker = wx.Panel(p, wx.ID_ANY, size=(10, 10)) marker.SetBackgroundColour(MagcalPanel._empty_color) sizer.Add(marker, flag=wx.ALIGN_CENTER) text = wx.StaticText(p, wx.ID_ANY) text.SetLabel('Sections not hit') sizer.Add(text, border=4, flag=wx.ALIGN_CENTER | wx.LEFT) marker = wx.Panel(p, wx.ID_ANY, size=(10, 10)) marker.SetBackgroundColour(MagcalPanel._filled_color) sizer.Add(marker, border=10, flag=wx.ALIGN_CENTER | wx.LEFT) text = wx.StaticText(p, wx.ID_ANY) text.SetLabel('Sections hit') sizer.Add(text, border=4, flag=wx.ALIGN_CENTER | wx.LEFT) return p