class MatplotlibWidget(Canvas): def __init__(self, parent=None, title='Title', xlabel='', ylabel='', dpi=100, hold=False): super(MatplotlibWidget, self).__init__(Figure()) self.setParent(parent) self.figure = Figure(dpi=dpi) self.figure.set_frameon(False) self.canvas = Canvas(self.figure) self.theplot = self.figure.add_subplot(111) # self.theplot.set_title(title) # self.theplot.set_xlabel(xlabel) # self.theplot.set_ylabel(ylabel) def plotDataPoints(self, im, CLim=4): self.theplot.imshow(im, vmin=0, vmax=CLim, cmap=plt.cm.PuRd) # if type(CLim) == float or type(CLim) == int or type(CLim) == long: # self.theplot.imshow(im,vmin = 0, vmax = CLim) # else: # self.theplot.imshow(im) self.draw() im = None
def __init__(self): super().__init__() main_layout = QW.QVBoxLayout(self) figure = Figure() figure.set_frameon(False) self.canvas = FigureCanvas(figure) self.canvas.setStyleSheet("background-color:transparent;") self.axis = self.canvas.figure.add_axes([0, 0.05, 0.2, 0.9]) self.upperTextBox = QW.QLineEdit() self.lowerTextBox = QW.QLineEdit() main_layout.addWidget(self.upperTextBox) main_layout.addWidget(self.canvas) main_layout.addWidget(self.lowerTextBox) self.upperTextBox.returnPressed.connect(self._update_bounds) self.lowerTextBox.returnPressed.connect(self._update_bounds) #: Colour bar limits self.bounds = [numpy.nan, numpy.nan] self.setFixedWidth(80)
def create_img(self, filename): fig = Figure() canvas = FigureCanvas(fig) self.build(fig) fig.set_frameon(False) # Background is hidden fig.set_size_inches(self.size[0], self.size[1]) # Set size fig.savefig(filename, dpi=self.dpi)
def __init__(self, xlim=(-0.5, 513.0), limupdate=(False, False)): #Set up the figure object and axis for displaying the heatmap fig = Figure() fig.set_frameon(False) self.axes = fig.add_axes([0.10, 0.10, 0.6, 0.8]) self.axes.set_xlabel('x (pixel widths)') self.axes.set_ylabel('y (pixel widths)') self.axes.set_xlim(*xlim) self.axes.set_ylim(-0.5, 513.0) self.axes.set_autoscalex_on(limupdate[0]) self.axes.set_autoscaley_on(limupdate[1]) #set up color bar as image self.colorbar = fig.add_axes([0.8, 0.15, 0.1, 0.8]) self.colorbar.xaxis.set_major_locator(plt.NullLocator()) FigureCanvas.__init__(self, fig) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
class MatplotlibWidget(Canvas): def __init__(self, parent=None, title='Title', xlabel='', ylabel='', dpi=100, hold=False): super(MatplotlibWidget, self).__init__(Figure()) self.setParent(parent) self.figure = Figure(dpi=dpi) self.figure.set_frameon(False) self.canvas = Canvas(self.figure) self.theplot = self.figure.add_subplot(111) # self.theplot.set_title(title) # self.theplot.set_xlabel(xlabel) # self.theplot.set_ylabel(ylabel) def plotDataPoints(self, im,CLim = 4): self.theplot.imshow(im,vmin = 0, vmax = CLim, cmap=plt.cm.PuRd) # if type(CLim) == float or type(CLim) == int or type(CLim) == long: # self.theplot.imshow(im,vmin = 0, vmax = CLim) # else: # self.theplot.imshow(im) self.draw() im = None
def print_result(self, print_context, render=True): figure = Figure(facecolor='white', figsize=(6,4.5)) figure.set_dpi(72) # Don't draw the frame, please. figure.set_frameon(False) canvas = _PlotResultCanvas(figure) axes = figure.add_subplot(111) self._replay(axes) width, height = figure.bbox.width, figure.bbox.height if render: cr = print_context.get_cairo_context() renderer = RendererCairo(figure.dpi) renderer.set_width_height(width, height) if hasattr(renderer, 'gc'): # matplotlib-0.99 and newer renderer.gc.ctx = cr else: # matplotlib-0.98 # RendererCairo.new_gc() does a restore to get the context back # to its original state after changes cr.save() renderer.ctx = cr figure.draw(renderer) if not hasattr(renderer, 'gc'): # matplotlib-0.98 # Reverse the save() we did before drawing cr.restore() return height
def print_result(self, print_context, render=True): figure = Figure(facecolor='white', figsize=(6, 4.5)) figure.set_dpi(72) # Don't draw the frame, please. figure.set_frameon(False) canvas = _PlotResultCanvas(figure) axes = figure.add_subplot(111) self._replay(axes) width, height = figure.bbox.width, figure.bbox.height if render: cr = print_context.get_cairo_context() renderer = RendererCairo(figure.dpi) renderer.set_width_height(width, height) if hasattr(renderer, 'gc'): # matplotlib-0.99 and newer renderer.gc.ctx = cr else: # matplotlib-0.98 # RendererCairo.new_gc() does a restore to get the context back # to its original state after changes cr.save() renderer.ctx = cr figure.draw(renderer) if not hasattr(renderer, 'gc'): # matplotlib-0.98 # Reverse the save() we did before drawing cr.restore() return height
prmsl = prmsl.extract(iris.Constraint(member=1)) mask = iris.load_cube("%s/fixed_fields/land_mask/opfc_global_2019.nc" % os.getenv('SCRATCH')) # Define the figure (page size, background color, resolution, ... fig = Figure( figsize=(19.2, 10.8), # Width, Height (inches) dpi=100, facecolor=(0.5, 0.5, 0.5, 1), edgecolor=None, linewidth=0.0, frameon=False, # Don't draw a frame subplotpars=None, tight_layout=None) fig.set_frameon(False) # Attach a canvas canvas = FigureCanvas(fig) # Projection for plotting cs = iris.coord_systems.RotatedGeogCS(args.pole_latitude, args.pole_longitude, args.npg_longitude) wind_pc = plot_cube(0.2, -180 / args.zoom, 180 / args.zoom, -90 / args.zoom, 90 / args.zoom) rw = iris.analysis.cartography.rotate_winds(u10m, v10m, cs) u10m = rw[0].regrid(wind_pc, iris.analysis.Linear()) v10m = rw[1].regrid(wind_pc, iris.analysis.Linear()) seq = (dte - datetime.datetime(2000, 1, 1)).total_seconds() / 3600 z = make_wind_seed(resolution=0.4, seed=0) wind_noise_field = wind_field(u10m,
def __init__(self, dataset): """ Construct the widget Args: dataset: xarray.Dataset """ super().__init__() main_layout = QW.QVBoxLayout(self) self.varlist = QW.QComboBox() self.xdim = QW.QComboBox() self.ydim = QW.QComboBox() header = QW.QGroupBox() header_layout = QW.QHBoxLayout(header) header_layout.addWidget(self.varlist) header_layout.addWidget(self.xdim) header_layout.addWidget(self.ydim) main_layout.addWidget(header) figure_group = QW.QGroupBox() figure_layout = QW.QHBoxLayout(figure_group) figure = Figure(tight_layout=True) figure.set_frameon(False) self.canvas = FigureCanvas(figure) self.canvas.setStyleSheet("background-color:transparent;") self.axis = self.canvas.figure.subplots() self.colorbar = ColorBarWidget() figure_layout.addWidget(self.canvas) figure_layout.addWidget(self.colorbar) main_layout.addWidget(figure_group) #: Dataset being inspected self.dataset = dataset # Setup list of variables, further setup is done by change_variable() classes = classify_vars(dataset) variables = sorted( [v for v in classes['data'] if dataset[v].ndim >= 2]) self.varlist.addItems(variables) # Connect slots self.varlist.currentIndexChanged.connect(self.change_variable) self.xdim.activated.connect(self.change_axes) self.ydim.activated.connect(self.change_axes) self.colorbar.valueChanged.connect(self.redraw) #: Currently active variable self.variable = None #: Values for non-axis dimensions self.dims = {} dims_group = QW.QGroupBox() dims_layout = QW.QVBoxLayout(dims_group) # Create widgets for coordinates for name in self.dataset.coords: self.dims[name] = DimensionWidget(self.dataset[name]) self.dims[name].valueChanged.connect(self.redraw) dims_layout.addWidget(self.dims[name]) # Create widgets for bare dims for name in self.dataset.dims: if name not in self.dims: da = xarray.DataArray(range(self.dataset.dims[name])) self.dims[name] = DimensionWidget(da) self.dims[name].valueChanged.connect(self.redraw) dims_layout.addWidget(self.dims[name]) main_layout.addWidget(dims_group) if len(variables) > 0: self.change_variable()
class PlotPanel(wx.Panel): zoom_levels = [100.0, 110.0, 125.0, 150.0, 200.0, 250.0, 300.0, 400.0] dose_contour_levels = [ 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 95.0, 98 - 0, 100.0, 102.0 ] def __init__(self, parent): wx.Panel.__init__(self, parent) self.is_closeable = False self.parent = parent self.active_plan = None self.plot_mouse_action = None pub.subscribe(self.on_patient_loaded, "patient.loaded.ini") pub.subscribe(self.set_active_image, "plot.image.active_id") pub.subscribe(self.voi_changed, "voi.selection_changed") pub.subscribe(self.plan_changed, "plan.active.changed") pub.subscribe(self.plan_field_changed, "plan.field.selection_changed") pub.subscribe(self.plan_dose_changed, "plan.dose.active_changed") pub.subscribe(self.plan_dose_removed, "plan.dose.removed") pub.subscribe(self.plan_let_added, "plan.let.added") pub.subscribe(self.plan_let_removed, "plan.let.removed") pub.subscribe(self.target_dose_changed, "plan.dose.target_dose_changed") self.plotmode = "Transversal" def __del__(self): pub.unsubscribe(self.on_patient_loaded, "patient.loaded.ini") pub.unsubscribe(self.set_active_image, "plot.image.active_id") pub.unsubscribe(self.voi_changed, "voi.selection_changed") pub.unsubscribe(self.plan_changed, "plan.active.changed") pub.unsubscribe(self.plan_field_changed, "plan.field.selection_changed") pub.unsubscribe(self.plan_dose_changed, "plan.dose.active_changed") pub.unsubscribe(self.plan_dose_removed, "plan.dose.removed") pub.unsubscribe(self.plan_let_added, "plan.let.added") pub.unsubscribe(self.plan_let_removed, "plan.let.removed") pub.unsubscribe(self.target_dose_changed, "plan.dose.target_dose_changed") def target_dose_changed(self, msg): self.Draw() def Init(self): self.plotutil = PlotUtil() self.figure = Figure(None, 100) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) # ~ self.canvas.SetDoubleBuffered(True) self.clear() self.plotutil.set_draw_in_gui(True) self.figure.set_frameon(True) rect = self.figure.patch rect.set_facecolor('black') def plan_dose_changed(self, msg): if msg.data["plan"] is self.active_plan: self.plotutil.set_dose(msg.data["dose"].get_dosecube()) self.Draw() def plan_field_changed(self, msg): self.Draw() def plan_dose_removed(self, msg): if msg.data["plan"] is self.active_plan: self.plotutil.set_dose(None) self.Draw() def plan_let_added(self, msg): if msg.data["plan"] is self.active_plan: self.plotutil.set_let(msg.data["let"]) self.Draw() def plan_let_removed(self, msg): if msg.data["plan"] is self.active_plan: self.plotutil.set_let(None) self.Draw() def plan_changed(self, msg): self.active_plan = msg.data if self.active_plan is None: self.plotutil.set_plan(None) self.plotutil.set_dose(None) self.plotutil.set_let(None) else: self.plotutil.set_plan(self.active_plan) doseobj = self.active_plan.get_dose() if doseobj is not None: self.plotutil.set_dose(doseobj.get_dosecube()) else: self.plotutil.set_dose(None) self.plotutil.set_let(self.active_plan.get_let()) self.Draw() def set_toolbar(self, toolbar): id = wx.NewId() selector = wx.Choice(toolbar, id) selector.Append("Transversal") selector.Append("Sagital") selector.Append("Coronal") idx = selector.FindString(self.plotmode) selector.Select(idx) toolbar.AddControl(selector) wx.EVT_CHOICE(selector, id, self.plot_mode_changed) id = wx.NewId() self.zoom_in_btn = toolbar.AddLabelTool( id, '', wx.Bitmap(get_resource_path('zoom_in.png'))) wx.EVT_MENU(toolbar, id, self.zoom_in) id = wx.NewId() self.zoom_out_btn = toolbar.AddLabelTool( id, '', wx.Bitmap(get_resource_path('zoom_out.png'))) wx.EVT_MENU(toolbar, id, self.zoom_out) def zoom_buttons_visible(self): zoom_idx = self.zoom_levels.index(self.plotutil.get_zoom()) self.zoom_in_btn.Enable(True) self.zoom_out_btn.Enable(True) if len(self.zoom_levels) == zoom_idx + 1: self.zoom_in_btn.Enable(False) if zoom_idx == 0: self.zoom_out_btn.Enable(False) def zoom_in(self, evt): zoom_idx = self.zoom_levels.index(self.plotutil.get_zoom()) zoom_idx += 1 if len(self.zoom_levels) > zoom_idx: zoom = self.zoom_levels[zoom_idx] self.plotutil.set_zoom(zoom) self.zoom_buttons_visible() self.Draw() def zoom_out(self, evt): zoom_idx = self.zoom_levels.index(self.plotutil.get_zoom()) zoom_idx -= 1 if zoom_idx >= 0: zoom = self.zoom_levels[zoom_idx] self.plotutil.set_zoom(zoom) self.zoom_buttons_visible() self.Draw() def plot_mode_changed(self, evt): self.plotmode = evt.GetString() self.plotutil.set_plot_plan(self.plotmode) self.image_idx = int(self.plotutil.get_images_count() / 2) self.clear() self.Draw() def clear(self): self.figure.clear() self.subplot = self.figure.add_subplot(111) self.plotutil.set_figure(self.subplot) def voi_changed(self, msg): voi = msg.data if voi.is_selected(): self.plotutil.add_voi(voi.voxelplan_voi) else: self.plotutil.remove_voi(voi.voxelplan_voi) self.Draw() def set_active_image(self, msg): if self.plotmode == "Transversal": self.image_idx = msg.data self.Draw() def on_patient_loaded(self, msg): self.data = msg.data ctx = self.data.get_images().get_voxelplan() self.plotutil.set_ct(ctx) self.image_idx = int(ctx.dimz / 2) self.setSize() self.bind_keys() def get_figure(self): return self.figure def bind_keys(self): self.Bind(wx.EVT_MOUSEWHEEL, self.on_mouse_wheel) self.Bind(wx.EVT_ENTER_WINDOW, self.on_mouse_enter) self.Bind(wx.EVT_LEAVE_WINDOW, self.on_mouse_leave) self.Bind(wx.EVT_SIZE, self.on_size) self.canvas.Bind(wx.EVT_KEY_DOWN, self.on_key_down) self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move_plot) self.canvas.mpl_connect('button_press_event', self.on_mouse_press_plot) self.canvas.mpl_connect('button_release_event', self.on_mouse_action_ended) self.canvas.mpl_connect('figure_leave_event', self.on_mouse_action_ended) def on_mouse_press_plot(self, evt): if evt.button is 3: pos = evt.guiEvent.GetPosition() standard = True if hasattr(self.plotutil, "contrast_bar"): bar = self.plotutil.contrast_bar if evt.inaxes is bar.ax: menu = self.right_click_contrast() standard = False if hasattr(self.plotutil, "dose_bar"): bar = self.plotutil.dose_bar if evt.inaxes is bar.ax: menu = self.right_click_dose() standard = False if standard: menu = self.normal_right_click_menu() wx.CallAfter(self.show_menu, menu) if self.canvas.HasCapture(): self.canvas.ReleaseMouse() elif evt.button is 1: if hasattr(self.plotutil, "contrast_bar"): bar = self.plotutil.contrast_bar if evt.inaxes is bar.ax: if evt.ydata >= 0.50: self.plot_mouse_action = "contrast_top" else: self.plot_mouse_action = "contrast_bottom" if hasattr(self.plotutil, "dose_bar"): bar = self.plotutil.dose_bar if evt.inaxes is bar.ax: if evt.ydata >= 0.50: self.plot_mouse_action = "dose_top" else: self.plot_mouse_action = "dose_bottom" if hasattr(self.plotutil, "let_bar"): bar = self.plotutil.let_bar if evt.inaxes is bar.ax: if evt.ydata >= 0.50: self.plot_mouse_action = "let_top" else: self.plot_mouse_action = "let_bottom" self.mouse_pos_ini = [evt.x, evt.y] evt.guiEvent.Skip() def show_menu(self, menu): self.PopupMenu(menu) def on_mouse_action_ended(self, evt): self.plot_mouse_action = None def on_mouse_move_plot(self, evt): pos = [evt.x, evt.y] if self.plot_mouse_action is not None: step = [ pos[0] - self.mouse_pos_ini[0], pos[1] - self.mouse_pos_ini[1] ] if self.plot_mouse_action == "contrast_top": contrast = self.plotutil.get_contrast() stepsize = np.log(contrast[1] - contrast[0]) contrast[1] -= stepsize * step[1] self.plotutil.set_contrast(contrast) elif self.plot_mouse_action == "contrast_bottom": contrast = self.plotutil.get_contrast() stepsize = np.log(contrast[1] - contrast[0]) contrast[0] -= stepsize * step[1] self.plotutil.set_contrast(contrast) elif self.plot_mouse_action == "dose_top": dose = self.plotutil.get_min_max_dose() dose[1] -= 0.30 * step[1] self.plotutil.set_dose_min_max(dose) elif self.plot_mouse_action == "dose_bottom": dose = self.plotutil.get_min_max_dose() dose[0] -= 0.30 * step[1] self.plotutil.set_dose_min_max(dose) elif self.plot_mouse_action == "let_top": let = self.plotutil.get_min_max_let() let[1] -= 0.30 * step[1] self.plotutil.set_let_min_max(let) elif self.plot_mouse_action == "let_bottom": let = self.plotutil.get_min_max_let() let[0] -= 0.30 * step[1] self.plotutil.set_let_min_max(let) self.Draw() elif evt.button == 1 and evt.inaxes is self.plotutil.fig_ct.axes: if not None in self.mouse_pos_ini: step = [ pos[0] - self.mouse_pos_ini[0], pos[1] - self.mouse_pos_ini[1] ] if self.plotutil.move_center(step): self.Draw() self.mouse_pos_ini = [evt.x, evt.y] if hasattr(self.plotutil, "fig_ct") and evt.inaxes is self.plotutil.fig_ct.axes: point = self.plotutil.pixel_to_pos( [round(evt.xdata), round(evt.ydata)]) text = "X: %.2f mm Y: %.2f mm / X: %d px Y: %d px" % ( point[1][0], point[1][1], point[0][0], point[0][1]) pub.sendMessage("statusbar.update", {"number": 1, "text": text}) dim = self.data.get_image_dimensions() if self.plotmode == "Transversal": pos = [round(evt.xdata), round(evt.ydata), self.image_idx] elif self.plotmode == "Sagital": pos = [ dim[0] - round(evt.xdata), self.image_idx, dim[2] - round(evt.ydata) ] elif self.plotmode == "Coronal": pos = [ self.image_idx, dim[1] - round(evt.xdata), dim[2] - round(evt.ydata) ] try: ct_value = self.data.get_image_cube()[pos[2], pos[1], pos[0]] text = "Value: %.1f" % (ct_value) plan = self.active_plan if plan is not None: dose = plan.get_dose_cube() if dose is not None: dose_value = dose[pos[2], pos[1], pos[0]] target_dose = plan.get_dose().get_dose() if not target_dose == 0.0: dose_value *= target_dose / 1000 text += " / Dose: %.1f Gy" % (float(dose_value)) else: dose_value /= 10 text += " / Dose: %.1f %%" % (float(dose_value)) let = plan.get_let_cube() if let is not None: let_value = let[pos[2], pos[1], pos[0]] text += " / LET: %.1f kev/um" % (let_value) except IndexError as e: pass pub.sendMessage("statusbar.update", {"number": 2, "text": text}) def normal_right_click_menu(self): menu = wx.Menu() voi_menu = wx.Menu() for voi in self.data.get_vois(): id = wx.NewId() item = voi_menu.AppendCheckItem(id, voi.get_name()) if voi.is_selected(): item.Check() wx.EVT_MENU(self, id, self.menu_voi_selected) if voi_menu.GetMenuItemCount() > 0: menu.AppendSubMenu(voi_menu, "Vois") view_menu = wx.Menu() active_plan = self.active_plan if active_plan is not None: dose = active_plan.get_dose() dose_type_menu = wx.Menu() if dose is not None: id = wx.NewId() item = view_menu.AppendCheckItem(id, "View Dose") if self.plotutil.get_dose() is not None: item.Check() wx.EVT_MENU(self, id, self.toogle_dose) id = wx.NewId() item = dose_type_menu.Append(id, "Color wash") wx.EVT_MENU(self, id, self.change_dose_to_colorwash) id = wx.NewId() item = dose_type_menu.Append(id, "Contour") wx.EVT_MENU(self, id, self.change_dose_to_contour) menu.AppendSubMenu(dose_type_menu, "Dose Visalization") if self.plotutil.get_dose_plot() == "contour": dose_contour_menu = wx.Menu() for level in self.dose_contour_levels: id = wx.NewId() item = dose_contour_menu.AppendCheckItem( id, "%d %%" % level) for contour in self.plotutil.get_dose_contours(): if contour["doselevel"] == level: item.Check() wx.EVT_MENU(self, id, self.toogle_dose_contour) menu.AppendSubMenu(dose_contour_menu, "Dose Contour levels") let = active_plan.get_let() if let is not None: id = wx.NewId() item = view_menu.AppendCheckItem(id, "View LET") if self.plotutil.get_let() is not None: item.Check() wx.EVT_MENU(self, id, self.toogle_let) if view_menu.GetMenuItemCount() > 0: menu.AppendSubMenu(view_menu, "View") field_menu = wx.Menu() for field in active_plan.get_fields(): id = wx.NewId() item = field_menu.AppendCheckItem(id, field.get_name()) if field.is_selected(): item.Check() wx.EVT_MENU(self, id, self.menu_field_selected) if field_menu.GetMenuItemCount() > 0: menu.AppendSubMenu(field_menu, "Fields") jump_menu = wx.Menu() id = wx.NewId() item = jump_menu.Append(id, "First") wx.EVT_MENU(self, id, self.jump_to_first) id = wx.NewId() item = jump_menu.Append(id, "Middle") wx.EVT_MENU(self, id, self.jump_to_middle) id = wx.NewId() item = jump_menu.Append(id, "Last") wx.EVT_MENU(self, id, self.jump_to_last) menu.AppendSubMenu(jump_menu, "Jump To") return menu def right_click_dose(self): menu = wx.Menu() id = wx.NewId() item = menu.Append(id, "Reset") wx.EVT_MENU(menu, id, self.reset_dose_range) colormap_menu = wx.Menu() id = wx.NewId() colormap_menu.Append(id, "Continuous") wx.EVT_MENU(colormap_menu, id, self.set_colormap_dose) id = wx.NewId() colormap_menu.Append(id, "Discrete") wx.EVT_MENU(colormap_menu, id, self.set_colormap_dose) item = menu.AppendSubMenu(colormap_menu, "Colorscale") scale_menu = wx.Menu() id = wx.NewId() scale_menu.Append(id, "Auto") wx.EVT_MENU(scale_menu, id, self.set_dose_scale) if self.active_plan.get_dose().get_dose() > 0.0: id = wx.NewId() scale_menu.Append(id, "Absolute") wx.EVT_MENU(scale_menu, id, self.set_dose_scale) id = wx.NewId() scale_menu.Append(id, "Relative") wx.EVT_MENU(scale_menu, id, self.set_dose_scale) item = menu.AppendSubMenu(scale_menu, "Scale") return menu def right_click_contrast(self): menu = wx.Menu() id = wx.NewId() item = menu.Append(id, "Reset") wx.EVT_MENU(menu, id, self.reset_contrast) return menu def set_colormap_dose(self, evt): colormap = plt.get_cmap(None) name = evt.GetEventObject().GetLabel(evt.GetId()) if name == "Discrete": colormap = cmap_discretize(colormap, 10) self.plotutil.set_colormap_dose(colormap) self.Draw() def set_dose_scale(self, evt): scale = {"auto": "auto", "absolute": "abs", "relative": "rel"} name = evt.GetEventObject().GetLabel(evt.GetId()) self.plotutil.set_dose_axis(scale[name.lower()]) self.Draw() def reset_dose_range(self, evt): self.plotutil.set_dose_min_max(0, 100) self.Draw() def reset_contrast(self, evt): contrast = [-100, 400] self.plotutil.set_contrast(contrast) self.Draw() def jump_to_first(self, evt): self.image_idx = 0 self.Draw() def jump_to_middle(self, evt): self.image_idx = self.plotutil.get_images_count() / 2 self.Draw() def jump_to_last(self, evt): self.image_idx = self.plotutil.get_images_count() - 1 self.Draw() def toogle_dose_contour(self, evt): value = float(evt.GetEventObject().GetLabel(evt.GetId()).split()[0]) if evt.IsChecked(): self.plotutil.add_dose_contour({"doselevel": value, "color": "b"}) else: for contour in self.plotutil.get_dose_contours(): if contour["doselevel"] == value: self.plotutil.remove_dose_contour(contour) self.Draw() def toogle_dose(self, evt): if self.plotutil.get_dose() is None: self.plotutil.set_dose(self.active_plan.get_dose().get_dosecube()) else: self.plotutil.set_dose(None) self.Draw() def toogle_let(self, evt): if self.plotutil.get_let() is None: self.plotutil.set_let(self.active_plan.get_let()) else: self.plotutil.set_let(None) self.Draw() def menu_voi_selected(self, evt): name = evt.GetEventObject().GetLabel(evt.GetId()) name = name.replace("__", "_") voi = self.data.get_vois().get_voi_by_name(name) if not voi is None: voi.toogle_selected() def menu_field_selected(self, evt): name = evt.GetEventObject().GetLabel(evt.GetId()) field = self.active_plan.get_fields().get_field_by_name(name) field.toogle_selected(self.active_plan) def change_dose_to_colorwash(self, evt): self.plotutil.set_dose_plot("colorwash") self.Draw() def change_dose_to_contour(self, evt): self.plotutil.set_dose_plot("contour") self.Draw() def on_size(self, evt): """Refresh the view when the size of the panel changes.""" self.setSize() def on_mouse_wheel(self, evt): delta = evt.GetWheelDelta() rot = evt.GetWheelRotation() rot = rot / delta if evt.ControlDown(): if (rot >= 1): self.zoom_in(None) elif (rot < 1): self.zoom_out(None) return n_images = self.data.get_images().get_voxelplan().dimz if n_images: if (rot >= 1): if (self.image_idx > 0): self.image_idx -= 1 self.Draw() if (rot <= -1): if (self.image_idx < self.plotutil.get_images_count() - 1): self.image_idx += 1 self.Draw() def on_key_down(self, evt): prevkey = [wx.WXK_UP, wx.WXK_PAGEUP] nextkey = [wx.WXK_DOWN, wx.WXK_PAGEDOWN] code = evt.GetKeyCode() if code in prevkey: if (self.image_idx > 0): self.image_idx -= 1 self.Draw() elif code in nextkey: if (self.image_idx < self.plotutil.get_images_count() - 1): self.image_idx += 1 self.Draw() def on_mouse_enter(self, evt): """Set a flag when the cursor enters the window.""" self.mouse_in_window = True def on_mouse_leave(self, evt): """Set a flag when the cursor leaves the window.""" self.mouse_in_window = False def setSize(self): size = self.parent.GetClientSize() size[1] = size[1] - 40 size[0] = size[0] - 5 pixels = tuple(size) self.canvas.SetSize(pixels) self.figure.set_size_inches( float(pixels[0]) / self.figure.get_dpi(), float(pixels[1]) / self.figure.get_dpi()) self.Draw() def Draw(self): self.plotutil.plot(self.image_idx) self.figure.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) # self.figure.tight_layout(pad=0.0) if hasattr(self.plotutil, "dose_bar"): bar = self.plotutil.dose_bar bar.ax.yaxis.label.set_color('white') bar.ax.tick_params(axis='y', colors='white', labelsize=8) if hasattr(self.plotutil, "let_bar"): bar = self.plotutil.let_bar bar.ax.yaxis.label.set_color('white') bar.ax.yaxis.label.set_color('white') bar.ax.tick_params(axis='y', colors='white', labelsize=8) if hasattr(self.plotutil, "contrast_bar"): bar = self.plotutil.contrast_bar bar.ax.yaxis.label.set_color('white') bar.ax.yaxis.set_label_position('left') [t.set_color("white") for t in bar.ax.yaxis.get_ticklabels()] [t.set_size(8) for t in bar.ax.yaxis.get_ticklabels()] # bar.ax.tick_params(axis='y', colors='white',labelsize=8,labelleft=True,labelright=False) self.canvas.draw()
class MplGraphQt5Widget(QWidget): def __init__(self, parent=None): super(MplGraphQt5Widget, self).__init__(parent) self.width = 3 self.height = 3 self.dpi = 100 self._dataY = np.array([]) self._dataX = np.array([]) self._spCols = 1 self._spRows = 1 self.all_sp_axes = [] self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi) self.all_sp_axes.append(self.fig.add_subplot(self._spCols, self._spRows, 1)) self.fig.set_frameon(False) self.fig.set_tight_layout(True) self.canvas = Canvas(self.fig) self._navBarOn = False self.mpl_toolbar = NavigationToolbar(self.canvas, parent) self.mpl_toolbar.dynamic_update() self.canvas.mpl_connect('key_press_event', self.on_key_press) self.canvas.mpl_connect('button_press_event', self.on_button_press) self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move) self.canvas.setFocusPolicy(Qt.ClickFocus) self.canvas.setFocus() self.canvas.setParent(parent) self.canvas.clearMask() self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.canvas.updateGeometry() vbox = QVBoxLayout() vbox.addWidget(self.canvas) vbox.addWidget(self.mpl_toolbar) if not self._navBarOn: self.mpl_toolbar.hide() self.setLayout(vbox) def get_icon(name): """Return Matplotlib icon *name*""" return QIcon(osp.join(rcParams['datapath'], 'images', name)) key_pressed = pyqtSignal(object, name='keyPressed') def on_key_press(self, event): self.key_pressed.emit(event) key_press_handler(event, self.canvas, self.mpl_toolbar) button_pressed = pyqtSignal(object, name='buttonPressed') def on_button_press(self, event): self.button_pressed.emit(event) key_press_handler(event, self.canvas, self.mpl_toolbar) mouse_move = pyqtSignal(object, name='mouseMoved') def on_mouse_move(self, event): self.mouse_move.emit(event) key_press_handler(event, self.canvas, self.mpl_toolbar) def generateNewAxes(self): for ax in self.all_sp_axes: self.fig.delaxes(ax) self.all_sp_axes = [] numOfAxes = (self._spRows*self._spCols)+1 for i in np.arange(1,numOfAxes): self.all_sp_axes.append(self.fig.add_subplot(self._spRows, self._spCols, i)) self.canvas.setGeometry(100, 100, 300, 300) #Used to update the new number of axes self.canvas.updateGeometry() #This will bring the size of the canvas back to the original (defined by the vbox) spRowsChanged = pyqtSignal(int) def getspRows(self): return self._spRows @pyqtSlot(int) def setspRows(self, spRows): self._spRows = spRows self.generateNewAxes() self.spRowsChanged.emit(spRows) def resetspRows(self): self.setspRows(1) spRows = pyqtProperty(int, getspRows, setspRows, resetspRows) spColsChanged = pyqtSignal(int) def getspCols(self): return self._spCols @pyqtSlot(int) def setspCols(self, spCols): self._spCols = spCols self.generateNewAxes() self.spRowsChanged.emit(spCols) def resetspCols(self): self.setspCols(1) spCols = pyqtProperty(int, getspCols, setspCols, resetspCols) dataChanged = pyqtSignal(bool) def get_Y_data(self): return self._dataY @pyqtSlot(int) def set_Y_data(self, y_data): self._dataY = y_data self.dataChanged.emit(True) def plot(self, on_axes=0): if np.size(self._dataX) == 0: self.all_sp_axes[on_axes].plot(self._dataY) else: self.all_sp_axes[on_axes].plot(self._dataX, self._dataY) def getNavBarOn(self): return self._navBarOn def setNavBarOn(self, navBarOn): self._navBarOn = navBarOn if not navBarOn: self.mpl_toolbar.hide() else: self.mpl_toolbar.show() def resetNavBarOn(self): self._navBarOn = True navBarOn = pyqtProperty(bool, getNavBarOn, setNavBarOn, resetNavBarOn) @pyqtSlot(bool) def set_autoscale(self, autoscale): for axis in self.all_sp_axes: axis.set_autoscale(autoscale)
def simple_chart(request): """ The first try at creating analytics server side with matplotlib """ # Get the specific model field names that will appear # on the X axis # Method 1 - get_all_field_names() model_names = School._meta.get_all_field_names() # Determine the qty of fields in the model num_obj_returned = len(model_names) # The chart index, is where the x ticks will be placed chart_index = np.arange(num_obj_returned) # Populating the Y axis with random numbers 0 - 1000 y_values = [] for i in range(num_obj_returned): y_values.append(random.randint(0, 100000)) # Populating the x axis, not the labels, with a numpy array # remember - .25 is array based x_values = chart_index - .25 ##### Chart Styling ###### chart_height = 4 chart_length = 5 chart_label = "First Analytic Chart Label" xlabel = "This is the X Label" ylabel = "This is the y label" display_frame = False tight_layout = True chart_title_align = 'center' xtick_alignment = 'center' # Create a figure objectm with tight_layout automatically # adjusts subplot(s) fits in to the figure area fig = Figure() fig.set_tight_layout(tight_layout) fig.set_size_inches(chart_length, chart_height) fig.set_frameon(display_frame) # create an axis, this is 1 row, 1 column, and 1 cell or 111 ax = fig.add_subplot(111) # Actually create the bar chart here # in this case, x asis is just ax.bar(x_values, y_values, color='grey', width=.5) # this sets the xlim just a little to the right on the y axis # and aligns it on the right also ax.set_xlim(xmin=-0.25, xmax=num_obj_returned - 0.75) # Where the x ticks are placed and set the labels ax.set_xticks(chart_index) ax.set_xticklabels(model_names, ha=xtick_alignment) # Set the chart title ax.set_title(chart_label, loc=chart_title_align) # Set the x and y axis label ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) # The canvas the figure renders into. # Calls the draw and print fig # methods, creates the renderers, etc... canvas = FigureCanvas(fig) # HttpResponse represents an outgoing HTTP response, # including HTTP headers, cookies and body content response = HttpResponse(content_type='image/png') canvas.print_png(response) return response
class MplGraphWidget(QtGui.QWidget): def __init__(self, parent=None, width=3, height=3, dpi=100): super(MplGraphWidget, self).__init__(parent) self._dataY = np.array([]) self._dataX = np.array([]) self._spCols = 1 self._spRows = 1 self.all_sp_axes = [] self.fig = Figure(figsize=(width, height), dpi=dpi) self.all_sp_axes.append( self.fig.add_subplot(self._spCols, self._spRows, 1)) self.fig.set_frameon(False) self.fig.set_tight_layout(True) self.canvas = Canvas(self.fig) self._navBarOn = True self.mpl_toolbar = NavigationToolbar(self.canvas, parent) self.canvas.mpl_connect('key_press_event', self.on_key_press) self.canvas.mpl_connect('button_press_event', self.on_button_press) self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move) self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus) self.canvas.setFocus() self.canvas.setParent(parent) self.canvas.clearMask() self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.canvas.updateGeometry() vbox = QtGui.QVBoxLayout() vbox.addWidget(self.canvas) if self._navBarOn: vbox.addWidget(self.mpl_toolbar) self.setLayout(vbox) key_pressed = QtCore.pyqtSignal(object, name='keyPressed') def on_key_press(self, event): self.key_pressed.emit(event) key_press_handler(event, self.canvas, self.mpl_toolbar) button_pressed = QtCore.pyqtSignal(object, name='buttonPressed') def on_button_press(self, event): self.button_pressed.emit(event) key_press_handler(event, self.canvas, self.mpl_toolbar) mouse_move = QtCore.pyqtSignal(object, name='mouseMoved') def on_mouse_move(self, event): self.mouse_move.emit(event) key_press_handler(event, self.canvas, self.mpl_toolbar) def get_icon(name): """Return Matplotlib icon *name*""" return QtGui.QIcon(osp.join(rcParams['datapath'], 'images', name)) def generateNewAxes(self): for ax in self.all_sp_axes: self.fig.delaxes(ax) self.all_sp_axes = [] numOfAxes = (self._spRows * self._spCols) + 1 for i in np.arange(1, numOfAxes): self.all_sp_axes.append( self.fig.add_subplot(self._spRows, self._spCols, i)) self.canvas.setGeometry(100, 100, 300, 300) #Used to update the new number of axes self.canvas.updateGeometry( ) #This will bring the size of the canvas back to the original (defined by the vbox) spRowsChanged = QtCore.pyqtSignal(int) def getspRows(self): return self._spRows @QtCore.pyqtSlot(int) def setspRows(self, spRows): self._spRows = spRows self.generateNewAxes() self.spRowsChanged.emit(spRows) def resetspRows(self): self.setspRows(1) spRows = QtCore.pyqtProperty(int, getspRows, setspRows, resetspRows) spColsChanged = QtCore.pyqtSignal(int) def getspCols(self): return self._spCols @QtCore.pyqtSlot(int) def setspCols(self, spCols): self._spCols = spCols self.generateNewAxes() self.spRowsChanged.emit(spCols) def resetspCols(self): self.setspCols(1) spCols = QtCore.pyqtProperty(int, getspCols, setspCols, resetspCols) dataChanged = QtCore.pyqtSignal(bool) def get_Y_data(self): return self._dataY @QtCore.pyqtSlot(int) def set_Y_data(self, y_data): self._dataY = y_data self.dataChanged.emit(True) def plot(self, on_axes=0): if np.size(self._dataX) == 0: self.all_sp_axes[on_axes].plot(self._dataY) else: self.all_sp_axes[on_axes].plot(self._dataX, self._dataY) def getNavBarOn(self): return self._navBarOn def setNavBarOn(self, navBarOn): self._navBarOn = navBarOn if not navBarOn: self.mpl_toolbar.hide() else: self.mpl_toolbar.show() def resetNavBarOn(self): self._navBarOn = True navBarOn = QtCore.pyqtProperty(bool, getNavBarOn, setNavBarOn, resetNavBarOn) # def getautoscale(self): # return self._autoscale # # def setautoscale(self, autoscale): # self._autoscale = autoscale # for axis in self.all_sp_axes: # axis.set_autoscale(autoscale) # # def resetautoscale(self): # self._autoscale = False # # autoscale = QtCore.pyqtProperty(bool, getautoscale, setautoscale, resetautoscale) @QtCore.pyqtSlot(bool) def set_autoscale(self, autoscale): for axis in self.all_sp_axes: axis.set_autoscale(autoscale)
class OneDimDraw(FigureCanvas): ''' class to carry out the creation of a matplotlib figure embedded into the cytostream application. The interactive matplotlib figure allowed the user to select channels and toggle samples within each channel. selectedFile - The currently selected file associated with the project -- see FileSelector class homeDir - home directory of the project i.e. '/.../cytostream/projects/foo' parent (optional) - A QtGui.QWidget() instance subset (optional) - Specifies the number of samples in a subset modelName (optional) - The currently selected model -- see FileSelector class modelType (optional) - The mode or type associated with a model (i.e. components, modes) background (optional) - for saving the figure a backgound should be rendered during plot generation Testing: this function may be tested by running: $ python OneDimViewer.py ''' def __init__(self,fcsFileList,masterChannelList,model,log,subset="original",parent=None,altDir=None, modelName=None, background=False, modelType=None): ## prepare plot environment self.fig = Figure() self.ax = self.fig.add_subplot(111) self.fig.set_frameon(background) self.selectedChannelInd = 0 self.selectedFileIndices = [0] self.colors = get_all_colors() self.lines = ['-','.','--','-.','o','d','s','^'] * 10 ## declare variables self.fcsFileList = fcsFileList self.masterChannelList = masterChannelList self.subset = subset ## create the plot self.make_plot(model,log,subset) ## initialization of the canvas FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) ## notify the system of updated policy FigureCanvas.updateGeometry(self) def get_line_attrs(self,fcsFileInd): line = int(np.floor(float(fcsFileInd) / float(len(self.colors)))) color = fcsFileInd % len(self.colors) return self.colors[color],self.lines[line] def make_plot(self,model,log,subset,buff=0.02): ## make all the line plots (dict key order : [fileInd][channelInd] self.plotDict = {} self.tagDict = {} ## determine max val for each channel self.maxVal = 0 count = 0 for fcsFileInd in range(len(self.fcsFileList)): count+=1 fcsFileName = re.sub("\.fcs|\.pickle|\.csv","",self.fcsFileList[fcsFileInd]) for channelInd in range(len(self.masterChannelList)): data,labels = fetch_plotting_events(fcsFileName,model,log,self.subset) events = [float(d) for d in data[:, channelInd]] newMax = np.max(events) if newMax > self.maxVal: self.maxVal = newMax for fcsFileInd in range(len(self.fcsFileList)): for channelInd in range(len(self.masterChannelList)): if fcsFileInd == 0 and channelInd == 0: visible = True else: visible = False self.make_line_plot(subset,model,log,fcsFileInd,channelInd,visible=visible) def make_line_plot(self,subset,model,log,fcsFileInd,channelInd,visible=False): fcsFileName = re.sub("\.fcs|\.pickle|\.csv","",self.fcsFileList[fcsFileInd]) fileChannelList = model.get_file_channel_list(fcsFileName) ## determine subset of events data,labels = fetch_plotting_events(fcsFileName,model,log,self.subset) events = [float(d) for d in data[:, channelInd]] fileChannelList = model.get_file_channel_list(fcsFileName) ## the histogram of the data #n, bins, patches = self.ax.hist(events, 50, normed=True,facecolor='blue', alpha=0.75) ## find the kernel density function self.pdfX = np.linspace(-200, self.maxVal,300) #np.min(events) approxPdf = gaussian_kde(events) if self.plotDict.has_key(str(fcsFileInd)) == False: self.plotDict[str(fcsFileInd)] = {} self.plotDict[str(fcsFileInd)][str(channelInd)] = approxPdf if visible == True: color,lineStyle = self.get_line_attrs(fcsFileInd) self.ax.plot(self.pdfX,approxPdf(self.pdfX),color=color,linestyle=lineStyle,linewidth=2.0,alpha=0.90) #self.draw() def paint(self,channel=None,fcsIndices=None): if channel != None: if self.masterChannelList.__contains__(channel) == False: print 'ERROR: master channel list does not contain', channel self.selectedChannelInd = self.masterChannelList.index(channel) if fcsIndices != None: self.selectedFileIndices = np.where(np.array(fcsIndices) == 1)[0] self.ax.clear() currentPlts = [] currentLabs = [] for fcsIndex in self.selectedFileIndices: approxPdf = self.plotDict[str(fcsIndex)][str(self.selectedChannelInd)] color,lineStyle = self.get_line_attrs(fcsIndex) pt = self.ax.plot(self.pdfX,approxPdf(self.pdfX),color=color,linestyle=lineStyle,linewidth=2.0,alpha=0.90) currentPlts.append(pt) currentLabs.append(self.fcsFileList[fcsIndex]) #if len(self.selectedFileIndices) > 0: # self.fig.legend( currentPlts, currentLabs, 'upper right', shadow=True) self.draw()