def __init__(self, **kwargs): super(VariableMeshPannerView, self).__init__(**kwargs) # Create the plot self.add_trait("field", DelegatesTo("vm_plot")) plot = self.vm_plot.plot img_plot = self.vm_plot.img_plot if self.use_tools: plot.tools.append(PanTool(img_plot)) zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) imgtool = ImageInspectorTool(img_plot) img_plot.tools.append(imgtool) overlay = ImageInspectorOverlay(component=img_plot, image_inspector=imgtool, bgcolor="white", border_visible=True) img_plot.overlays.append(overlay) image_value_range = DataRange1D(self.vm_plot.fid) cbar_index_mapper = LinearMapper(range=image_value_range) self.colorbar = ColorBar(index_mapper=cbar_index_mapper, plot=img_plot, padding_right=40, resizable='v', width=30) self.colorbar.tools.append( PanTool(self.colorbar, constrain_direction="y", constrain=True)) zoom_overlay = ZoomTool(self.colorbar, axis="index", tool_mode="range", always_on=True, drag_button="right") self.colorbar.overlays.append(zoom_overlay) # create a range selection for the colorbar range_selection = RangeSelection(component=self.colorbar) self.colorbar.tools.append(range_selection) self.colorbar.overlays.append( RangeSelectionOverlay(component=self.colorbar, border_color="white", alpha=0.8, fill_color="lightgray")) # we also want to the range selection to inform the cmap plot of # the selection, so set that up as well range_selection.listeners.append(img_plot) self.full_container = HPlotContainer(padding=30) self.container = OverlayPlotContainer(padding=0) self.full_container.add(self.colorbar) self.full_container.add(self.container) self.container.add(self.vm_plot.plot)
def _create_plot_component(): # Create a scalar field to colormap xs = linspace(0, 10, 600) ys = linspace(0, 5, 600) x, y = meshgrid(xs, ys) z = exp(-(x**2 + y**2) / 100) # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("imagedata", z) # Create the plot plot = Plot(pd) img_plot = plot.img_plot("imagedata", xbounds=(0, 10), ybounds=(0, 5), colormap=jet)[0] # Tweak some of the plot properties plot.title = "My First Image Plot" plot.padding = 50 # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False) img_plot.overlays.append(zoom) return plot
def _create_plot_component(self): pd = self.pd # Create the plot plot = Plot(pd, default_origin="top left",orientation="h") shape = pd.get_data('imagedata').shape plot.aspect_ratio = float(shape[1]) / shape[0] plot.x_axis.orientation = "top" #plot.y_axis.orientation = "top" #img_plot = plot.img_plot("imagedata",colormap = jet)[0] img_plot = plot.img_plot("imagedata",name = 'image', colormap = jet)[0] # Tweak some of the plot properties #plot.bgcolor = "white" plot.bgcolor = bg_color # Attach some tools to the plot plot.tools.append(PanTool(plot,constrain_key="shift", drag_button = 'right')) printer = DataPrinter(component=plot, process = self.process_selection) plot.tools.append(printer) plot.overlays.append(ZoomTool(component=plot, tool_mode="box", always_on=False)) #plot.title = 'Default image' imgtool = ImageInspectorTool(img_plot) img_plot.tools.append(imgtool) plot.overlays.append(ImageInspectorOverlay(component=img_plot, image_inspector=imgtool)) return plot
def _add_timePlot_tools(self, imgplot, token): """ Add LineInspectors, ImageIndexTool, and ZoomTool to the image plots. """ imgplot.overlays.append( ZoomTool(component=imgplot, tool_mode="box", enable_wheel=False, always_on=False)) imgplot.overlays.append( LineInspector(imgplot, axis="index_y", color="white", inspect_mode="indexed", write_metadata=True, is_listener=True)) imgplot.overlays.append( LineInspector(imgplot, axis="index_x", color="white", inspect_mode="indexed", write_metadata=True, is_listener=True)) imgplot.tools.append( ImageIndexTool(imgplot, token=token, callback=self._indexTime_callback, wheel_cb=self._wheel_callback)) imgplot.tools.append(PanTool(imgplot))
def render_image(self): plot = Plot(self.img_plotdata, default_origin="top left") img = plot.img_plot("imagedata", colormap=gray)[0] plot.title = "%s of %s: " % (self.img_idx + 1, self.numfiles) + self.titles[self.img_idx] plot.aspect_ratio = float(self.sig.data.shape[1]) / float( self.sig.data.shape[0]) #if not self.ShowCC: csr = CursorTool(img, drag_button='left', color='white', line_width=2.0) self.csr = csr csr.current_position = self.left, self.top img.overlays.append(csr) # attach the rectangle tool plot.tools.append(PanTool(plot, drag_button="right")) zoom = ZoomTool(plot, tool_mode="box", always_on=False, aspect_ratio=plot.aspect_ratio) plot.overlays.append(zoom) self.img_plot = plot return plot
def _create_plot(self, data, name, type="line"): p = Plot(self.plot_data) p.plot(data, name=name, title=name, type=type) p.tools.append(PanTool(p)) zoom = ZoomTool(component=p, tool_mode="box", always_on=False) p.overlays.append(zoom) p.title = name return p
def _hist_plot_default(self): plot = Plot(self.hist_plot_data, padding_left=50, padding_top=10, padding_right=10, padding_bottom=30) plot.plot(('x','y'), style='line', color='blue', name='hist') plot.index_axis.title = '# counts' plot.value_axis.title = '# occurences' plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) return plot
def _plot_xy8_default(self): plot = Plot(self.plot_xy8_data, padding_left=60, padding_top=25, padding_right=10, padding_bottom=50) plot.plot(('xy8_plot_x', 'xy8_plot_y'), style='line', color='blue') plot.index_axis.title = 'tau [micro-s]' plot.value_axis.title = 'Intensity [a.u.]' plot.title = 'xy8 raw data' plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) return plot
def _plot_density_default(self): plot = Plot(self.plot_density_data, padding_left=60, padding_top=25, padding_right=10, padding_bottom=50) plot.plot(('density_plot_x', 'density_plot_y'), style='line', color='blue') plot.index_axis.title = 'frequency [MHz]' plot.value_axis.title = 'spectral density [MHz]' plot.title = 'Spectral density' plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) return plot
def _create_TracePlot_component(self): plot = DataView(border_visible=True) line = LinePlot(value=ArrayDataSource(self.Trace), index=ArrayDataSource(numpy.arange(len(self.Trace))), color='blue', index_mapper=LinearMapper(range=plot.index_range), value_mapper=LinearMapper(range=plot.value_range)) plot.index_range.sources.append(line.index) plot.value_range.sources.append(line.value) plot.add(line) plot.index_axis.title = 'index' plot.value_axis.title = 'Fluorescence [ counts / s ]' plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) self.TraceLine = line return plot
def __init__(self, *l, **kw): # TODO: implement aspect ratio maintaining HasTraits.__init__(self, *l, **kw) #self.plotdata = ArrayPlotData(x=self.pointsx, y=self.pointsy) plot = Plot(self.plotdata) plot.plot(("x", "y")) plot.plot(("x", "y"), type='scatter') plot.tools.append(PanTool(plot, drag_button='left')) plot.tools.append(ZoomTool(plot, tool_mode='box')) plot.tools.append(DragZoom(plot, tool_mode='box', drag_button='right')) plot.tools.append(CustomSaveTool( plot)) #, filename='/home/pankaj/Desktop/file.png')) plot.tools.append(TraitsTool(plot)) self.plot = plot self.set_plotdata()
def _create_window(self, title, xtitle, x, ytitle, y, type="line", color="blue"): self.plotdata = ArrayPlotData(x=x, y=y) plot = ToolbarPlot(self.plotdata) plot.plot(('x', 'y'), type=type, color=color) plot.title = title plot.x_axis.title = xtitle plot.y_axis.title = ytitle self.plot = plot self._hid = 0 self._colors = ['blue', 'red', 'black', 'green', 'magenta', 'yellow'] # Add some tools self.plot.tools.append(PanTool(self.plot, constrain_key="shift")) self.plot.overlays.append(ZoomTool(component=self.plot, tool_mode="box", always_on=False)) return Window(self, -1, component=plot)
def _plot_xy8norm_default(self): plot = Plot(self.plot_xy8norm_data, padding_left=60, padding_top=25, padding_right=10, padding_bottom=50) plot.plot(('xy8norm_plot_x', 'xy8norm_plot_y'), style='line', color='blue') plot.index_axis.title = 'tau [micro-s]' plot.value_axis.title = 'normalized Intensity' plot.title = 'xy8 normalized to rabi contrast' plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) plot.y_axis.mapper.range.set(low=-0.1, high=1.1) return plot
def __init__(self, name, model, time_src): ''' Args: Returns: Raises: ''' self.name = name self.metrics = [] self.model = model self.plot_data = ArrayPlotData(index=time_src) self.plot_conactory = Plot( self.plot_data) #spacing=20, padding = 20, border_visible=False) self.plot_conactory.padding_bg_color = "white" self.plot_conactory.bgcolor = "white" self.plot_conactory.padding_left = 50 self.plot_conactory.padding_bottom = 17 self.plot_conactory.padding_right = 20 self.plot_conactory.padding_top = 2 self.saved_index_range = self.plot_conactory.index_range self.plot_conactory.legend.visible = True self.plot_conactory.legend.align = "ll" self.x_axis = self.plot_conactory.x_axis self.y_axis = self.plot_conactory.y_axis self.plot_conactory.legend.tools.append( MyLegendHighlighter(self.plot_conactory.legend, drag_button="left", modifier="shift")) self.pan_tool = PanTool(self.plot_conactory, constrain=True, constrain_direction="x") self.plot_conactory.tools.append(self.pan_tool) self.zoom_tool = ZoomTool( self.plot_conactory, drag_button="right", always_on=True, always_on_modifier="shift", tool_mode="range", axis="index", max_zoom_out_factor=1.0, ) self.plot_conactory.tools.append(self.zoom_tool) self.drag_zoom_tool = DragZoom(self.plot_conactory, drag_button="right") self.plot_conactory.tools.append(self.drag_zoom_tool)
def _plot_default(self): plot = Plot(self.plotdata) self.plotdata.set_data('t', self.t) self.plotdata.set_data('x', self.x) plot.plot(('t', 'x'), color='red', type_trait="plot_type", name='x') plot.legend.visible = True plot.title = "Stopped flow" plot.x_axis.title = 't' # Add pan and zoom to the plot plot.tools.append(PanTool(plot, constrain_key="shift")) zoom = ZoomTool(plot) plot.overlays.append(zoom) return plot
def __init__(self, **traits): super(LinePlot, self).__init__(**traits) x = np.linspace(-14, 14, 100) y = np.sin(x) * x**3 data = ArrayPlotData(x=x, y=y) plot = Plot(data) plot.plot(("x", "y"), type="line", color="blue") plot.title = "sin(x) * x^3" plot.tools.append(PanTool(plot)) plot.tools.append( DragZoom(plot, drag_button="right", maintain_aspect_ratio=False)) plot.overlays.append(ZoomTool(plot)) # plot.overlays.append(ZoomTool(plot, tool_mode="range", axis = "index", # always_on=True, always_on_modifier="control")) self.plot = plot self.data = data
def _create_HistPlot_component(self): plot = DataView(border_visible=True) line = LinePlot( index=ArrayDataSource(self.HistogramBins), value=ArrayDataSource(self.HistogramN), color='blue', #fill_color='blue', index_mapper=LinearMapper(range=plot.index_range), value_mapper=LinearMapper(range=plot.value_range)) plot.index_range.sources.append(line.index) plot.value_range.sources.append(line.value) plot.add(line) plot.index_axis.title = 'Fluorescence counts' plot.value_axis.title = 'number of occurences' plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) self.HistLine = line return plot
def _create_window(self, title, xtitle, x, ytitle, y, z): ''' - Left-drag pans the plot. - Mousewheel up and down zooms the plot in and out. - Pressing "z" brings up the Zoom Box, and you can click-drag a rectangular region to zoom. If you use a sequence of zoom boxes, pressing alt-left-arrow and alt-right-arrow moves you forwards and backwards through the "zoom history". ''' self._plotname = title # Create window self.data = ArrayPlotData() self.plot = Plot(self.data) self.update_plot(x, y, z) self.plot.title = title self.plot.x_axis.title = xtitle self.plot.y_axis.title = ytitle cmap_renderer = self.plot.plots[self._plotname][0] # Create colorbar self._create_colorbar() self._colorbar.plot = cmap_renderer self._colorbar.padding_top = self.plot.padding_top self._colorbar.padding_bottom = self.plot.padding_bottom # Add some tools self.plot.tools.append(PanTool(self.plot, constrain_key="shift")) self.plot.overlays.append( ZoomTool(component=self.plot, tool_mode="box", always_on=False)) # selection = ColormappedSelectionOverlay(cmap_renderer, fade_alpha=0.35, selection_type="mask") # cmap_renderer.overlays.append(selection) # Create a container to position the plot and the colorbar side-by-side container = HPlotContainer(use_backbuffer=True) container.add(self.plot) container.add(self._colorbar) self.container = container # Return a window containing our plot container return Window(self, -1, component=container)
def activate_template(self): """ Converts all contained 'TDerived' objects to real objects using the template traits of the object. This method must be overridden in subclasses. Returns ------- None """ # If our data sources are still unbound, then just exit; someone must # have marked them as optional: if ((self.index.context_data is Undefined) or (self.value.context_data is Undefined)): return # Create a plot data object and give it this data: pd = ArrayPlotData() pd.set_data('index', self.index.context_data) pd.set_data('value', self.value.context_data) # Create the plot: self.plot = plot = Plot(pd) plot.plot(('index', 'value'), type='scatter', index_sort='ascending', marker=self.marker, color=self.color, outline_color=self.outline_color, marker_size=self.marker_size, line_width=self.line_width, bgcolor='white') plot.set(padding_left=50, padding_right=0, padding_top=0, padding_bottom=20) # Attach some tools to the plot: plot.tools.append(PanTool(plot, constrain_key='shift')) zoom = SimpleZoom(component=plot, tool_mode='box', always_on=False) plot.overlays.append(zoom)
def _plot_default(self): self._pd = ArrayPlotData() self._pd.set_data("imagedata", self._image) plot = Plot(self._pd, default_origin="top left") plot.x_axis.orientation = "top" img_plot = plot.img_plot("imagedata")[0] plot.bgcolor = "white" # Tweak some of the plot properties plot.title = "Click to add points, press Enter to clear selection" plot.padding = 50 plot.line_width = 1 # Attach some tools to the plot pan = PanTool(plot, drag_button="right", constrain_key="shift") plot.tools.append(pan) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) return plot
def _create_plot_component(): # Create a scalar field to contour xs = linspace(-2 * pi, 2 * pi, 600) ys = linspace(-1.5 * pi, 1.5 * pi, 300) x, y = meshgrid(xs, ys) z = tanh(x * y / 6) * cosh(exp(-y**2) * x / 3) z = x * y # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("imagedata", z) # Create a contour polygon plot of the data plot = Plot(pd, default_origin="top left") plot.contour_plot("imagedata", type="poly", poly_cmap=jet, xbounds=(xs[0], xs[-1]), ybounds=(ys[0], ys[-1])) # Create a contour line plot for the data, too plot.contour_plot("imagedata", type="line", xbounds=(xs[0], xs[-1]), ybounds=(ys[0], ys[-1])) # Tweak some of the plot properties plot.title = "My First Contour Plot" plot.padding = 50 plot.bg_color = "white" plot.fill_padding = True # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) return plot
def __init__(self, *l, **kw): # TODO: implement aspect ratio maintaining HasTraits.__init__(self, *l, **kw) #self.plotdata = ArrayPlotData(x=self.pointsx, y=self.pointsy) plot = Plot(self.plotdata) renderer = plot.plot(("x", "y")) #lineplot = create_line_plot((self.pointsx,self.pointsy), width=2.0) #lineplot.tools.append(PanTool(lineplot, drag_button='middle')) #lineplot.tools.append(ZoomTool(lineplot, tool_mode='box')) plot.tools.append(PanTool(plot, drag_button='left')) plot.tools.append(ZoomTool(plot, tool_mode='box')) plot.tools.append(DragZoom(plot, tool_mode='box', drag_button='right')) plot.tools.append(CustomSaveTool( plot)) #, filename='/home/pankaj/Desktop/file.png')) #plot.overlays.append(PlotLabel('Section : %s' % self.section.type,component=plot)) #plot.tools.append(PlotToolbar(plot)) plot.tools.append(TraitsTool(plot)) #plot.tools.append(ZoomTool(plot, tool_mode='box', axis='index', drag_button='right', always_on=True)) #plot.aspect_ratio = 3 #plot.request_redraw() #print plot.bounds #plot.aspect_ratio = 1 #plot.bounds = [500,300] #print plot.bounds #plot.range2d = DataRange2D(low=(0,-.5), high=(1,0.5)) #print plot.bounds for renderer in chain(*plot.plots.values()): renderer.index_mapper.stretch_data = False renderer.value_mapper.stretch_data = False renderer.index_mapper.range.low = 0 renderer.index_mapper.range.high = 1 renderer.value_mapper.range.low = -3 / 8. renderer.value_mapper.range.high = 3 / 8. self.plot = plot
def get_plot(self): pixel_sizes = self.data_source.pixel_sizes shape = self.data.shape[1:] m = min(pixel_sizes) s = [int(d * sz / m) for d, sz in zip(shape, pixel_sizes)] plot_sizes = dict(xy=(s[1], s[0])) plot = Plot( self.plotdata, padding=30, fixed_preferred_size=plot_sizes['xy'], ) image = plot.img_plot('xy', colormap=bone)[0] image.overlays.append(ZoomTool(image)) image.tools.append(PanTool(image, drag_button='right')) imgtool = ImageInspectorTool(image) image.tools.append(imgtool) overlay = ImageInspectorOverlay(component=image, bgcolor='white', image_inspector=imgtool) image.overlays.append(overlay) self.image = image self.plots = dict(xy=image) return plot
class Demo(HasTraits): plot = Instance(Component) fileName = "clusters.cpickle" case = List(UncertaintyValue) cases = {} defaultCase = [] # Attributes to use for the plot view. size = (400, 1600) traits_view = View(Group( Group(Item('plot', editor=ComponentEditor(size=size), show_label=False), orientation="vertical", show_border=True, scrollable=True), Group(Item('case', editor=TabularEditor(adapter=CaseAdapter(can_edit=False)), show_label=False), orientation="vertical", show_border=True), layout='split', orientation='horizontal'), title='Interactive Lines', resizable=True) def setFileName(self, newName): self.fileName = newName def _update_case(self, name): if name: self.case = self.cases.get(name) else: self.case = self.defaultCase def _plot_default(self): #load the data to visualize. # it is a list of data in the 'results' format, each belonging to a cluster - gonenc resultsList = cPickle.load(open(self.fileName, 'r')) #get the names of the outcomes to display outcome = [] for entry in resultsList: a = entry[0][1].keys() outcome.append(a[0]) # outcome = resultsList[0][0][1].keys() # pop the time axis from the list of outcomes # outcome.pop(outcome.index('TIME')) x = resultsList[0][0][1]['TIME'] # the list and number of features (clustering related) stored regarding each run features = resultsList[0][0][0][0].keys() noFeatures = len(features) # Iterate over each cluster to prepare the cases corresponding to indivisdual runs in # each cluster plot. Each case is labeled as, e.g., y1-2 (3rd run in the 2nd cluster) - gonenc for c, results in enumerate(resultsList): for j, aCase in enumerate(results): aCase = [ UncertaintyValue(name=key, value=value) for key, value in aCase[0][0].items() ] self.cases['y' + str(c) + '-' + str(j)] = aCase # for j, aCase in enumerate(results): # aCase = [UncertaintyValue(name="blaat", value=aCase[0][0])] # self.cases['y'+str(j)] = aCase #make an empty case for default. #if you have multiple datafields associated with a run, iterate over #the keys of a dictionary of a case, instead of over lenght(2) case = [] for i in range(noFeatures): case.append(UncertaintyValue(name='Default', value='None')) self.case = case self.defaultCase = case # Create some x-y data series to plot pds = [] # enumerate over the results of all clusters for c, results in enumerate(resultsList): pd = ArrayPlotData(index=x) for j in range(len(results)): data = np.array(results[j][1].get(outcome[c])) print "y" + str(c) + '-' + str(j) pd.set_data("y" + str(c) + '-' + str(j), data) pds.append(pd) # Create a container and add our plots container = GridContainer(bgcolor="lightgray", use_backbuffer=True, shape=(len(resultsList), 1)) #plot data tools = [] for c, results in enumerate(resultsList): pd1 = pds[c] # Create some line plots of some of the data plot = Plot(pd1, title='Cluster ' + str(c), border_visible=True, border_width=1) plot.legend.visible = False #plot the results for i in range(len(results)): plotvalue = "y" + str(c) + '-' + str(i) print plotvalue color = colors[i % len(colors)] plot.plot(("index", plotvalue), name=plotvalue, color=color) #make sure that the time axis runs in the right direction for value in plot.plots.values(): for entry in value: entry.index.sort_order = 'ascending' # Attach the selector tools to the plot selectorTool1 = LineSelectorTool(component=plot) plot.tools.append(selectorTool1) tools.append(selectorTool1) # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) container.add(plot) #make sure the selector tools knows the main screen for tool in tools: tool._demo = self return container
def _create_plot_component(self): # Create a plot data object and give it this data self.pd = ArrayPlotData() self.pd.set_data("imagedata", self.data[self.data_name]) # Create the plot self.tplot = Plot(self.pd, default_origin="top left") self.tplot.x_axis.orientation = "top" self.tplot.img_plot( "imagedata", name="my_plot", #xbounds=(0,10), #ybounds=(0,10), colormap=jet) # Tweak some of the plot properties self.tplot.title = "Matrix" self.tplot.padding = 50 # Right now, some of the tools are a little invasive, and we need the # actual CMapImage object to give to them self.my_plot = self.tplot.plots["my_plot"][0] # Attach some tools to the plot self.tplot.tools.append(PanTool(self.tplot)) zoom = ZoomTool(component=self.tplot, tool_mode="box", always_on=False) self.tplot.overlays.append(zoom) # my custom tool to get the connection information self.custtool = CustomTool(self.tplot) self.tplot.tools.append(self.custtool) # Create the colorbar, handing in the appropriate range and colormap colormap = self.my_plot.color_mapper self.colorbar = ColorBar( index_mapper=LinearMapper(range=colormap.range), color_mapper=colormap, plot=self.my_plot, orientation='v', resizable='v', width=30, padding=20) self.colorbar.padding_top = self.tplot.padding_top self.colorbar.padding_bottom = self.tplot.padding_bottom # create a range selection for the colorbar self.range_selection = RangeSelection(component=self.colorbar) self.colorbar.tools.append(self.range_selection) self.colorbar.overlays.append( RangeSelectionOverlay(component=self.colorbar, border_color="white", alpha=0.8, fill_color="lightgray")) # we also want to the range selection to inform the cmap plot of # the selection, so set that up as well self.range_selection.listeners.append(self.my_plot) # Create a container to position the plot and the colorbar side-by-side container = HPlotContainer(use_backbuffer=True) container.add(self.tplot) container.add(self.colorbar) container.bgcolor = "white" return container
class Demo(HasTraits): plot = Instance(Component) fileName = "default.txt" case = List(UncertaintyValue) cases = {} defaultCase = [] # Attributes to use for the plot view. size = (400, 250) traits_view = View(Group( Group(Item('plot', editor=ComponentEditor(size=size), show_label=False), orientation="vertical", show_border=True), Group(Item('case', editor=TabularEditor(adapter=CaseAdapter(can_edit=False)), show_label=False), orientation="vertical", show_border=True), layout='split', orientation='horizontal'), title='Interactive Lines', resizable=True) def setFileName(self, newName): self.fileName = newName def _update_case(self, name): if name: self.case = self.cases.get(name) else: self.case = self.defaultCase def _plot_default(self): results = cPickle.load(open(self.fileName, 'r')) outcomes = results[0][1].keys() outcomes.pop(outcomes.index('TIME')) x = results[0][1]['TIME'] for j, aCase in enumerate(results): aCase = [ UncertaintyValue(name=key, value=value) for key, value in aCase[0][0].items() ] self.cases['y' + str(j)] = aCase uncertainties = results[0][0][0] uncertaintynames = uncertainties.keys() uncertaintyvalues = [] for key in uncertainties.keys(): uncertaintyvalues.append(uncertainties[key]) case = [] for i in range(len(uncertainties)): case.append( UncertaintyValue(name=str(uncertaintynames[i]), value="")) #haydaa self.case = case self.defaultCase = case # Create some x-y data series to plot pds = [] for i, outcome in enumerate(outcomes): pd = ArrayPlotData(index=x) for j in range(len(results)): pd.set_data("y" + str(j), results[j][1].get(outcome)) pds.append(pd) # Create a container and add our plots container = GridContainer(bgcolor="lightgray", use_backbuffer=True, shape=(1, 1)) #plot data tools = [] for j in range(len(outcomes)): pd1 = pds[j] # Create some line plots of some of the data plot = Plot(pd1, title=outcomes[j], border_visible=True, border_width=1) plot.legend.visible = False for i in range(len(results)): plotvalue = "y" + str(i) color = colors[i % len(colors)] plot.plot(("index", plotvalue), name=plotvalue, color=color) for value in plot.plots.values(): for entry in value: entry.index.sort_order = 'ascending' # Attach the selector tools to the plot selectorTool1 = LineSelectorTool(component=plot) plot.tools.append(selectorTool1) tools.append(selectorTool1) # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) container.add(plot) #make sure the selector tools know each other for tool in tools: tool._demo = self return container
def _end_pan(self, event): if hasattr(event, "bid"): event.window.release_blob(event.bid) PanTool._end_pan(self, event)
def panning_mouse_move(self,event): PanTool.panning_mouse_move(self,event) self.component.immediate_invalidate()
def __init__(self,xdata=None,ydata=None,weights=None,model=None, include_models=None,exclude_models=None,fittype=None,**traits): """ :param xdata: the first dimension of the data to be fit :type xdata: array-like :param ydata: the second dimension of the data to be fit :type ydata: array-like :param weights: The weights to apply to the data. Statistically interpreted as inverse errors (*not* inverse variance). May be any of the following forms: * None for equal weights * an array of points that must match `ydata` * a 2-sequence of arrays (xierr,yierr) such that xierr matches the `xdata` and yierr matches `ydata` * a function called as f(params) that returns an array of weights that match one of the above two conditions :param model: the initial model to use to fit this data :type model: None, string, or :class:`pymodelfit.core.FunctionModel1D` instance. :param include_models: With `exclude_models`, specifies which models should be available in the "new model" dialog (see `models.list_models` for syntax). :param exclude_models: With `include_models`, specifies which models should be available in the "new model" dialog (see `models.list_models` for syntax). :param fittype: The fitting technique for the initial fit (see :class:`pymodelfit.core.FunctionModel`). :type fittype: string kwargs are passed in as any additional traits to apply to the application. """ self.modelpanel = View(Label('empty'),kind='subpanel',title='model editor') self.tmodel = TraitedModel(model) if model is not None and fittype is not None: self.tmodel.model.fittype = fittype if xdata is None or ydata is None: if not hasattr(self.tmodel.model,'data') or self.tmodel.model.data is None: raise ValueError('data not provided and no data in model') if xdata is None: xdata = self.tmodel.model.data[0] if ydata is None: ydata = self.tmodel.model.data[1] if weights is None: weights = self.tmodel.model.data[2] self.on_trait_change(self._paramsChanged,'tmodel.paramchange') self.modelselector = NewModelSelector(include_models,exclude_models) self.data = [xdata,ydata] if weights is None: self.weights = np.ones_like(xdata) self.weighttype = 'equal' else: self.weights = np.array(weights,copy=True) self.savews = True weights1d = self.weights while len(weights1d.shape)>1: weights1d = np.sum(weights1d**2,axis=0) pd = ArrayPlotData(xdata=self.data[0],ydata=self.data[1],weights=weights1d) self.plot = plot = Plot(pd,resizable='hv') self.scatter = plot.plot(('xdata','ydata','weights'),name='data', color_mapper=_cmapblack if self.weights0rem else _cmap, type='cmap_scatter', marker='circle')[0] self.errorplots = None if not isinstance(model,FunctionModel1D): self.fitmodel = True self.updatemodelplot = False #force plot update - generates xmod and ymod plot.plot(('xmod','ymod'),name='model',type='line',line_style='dash',color='black',line_width=2) del plot.x_mapper.range.sources[-1] #remove the line plot from the x_mapper source so only the data is tied to the scaling self.on_trait_change(self._rangeChanged,'plot.index_mapper.range.updated') self.pantool = PanTool(plot,drag_button='left') plot.tools.append(self.pantool) self.zoomtool = ZoomTool(plot) self.zoomtool.prev_state_key = KeySpec('a') self.zoomtool.next_state_key = KeySpec('s') plot.overlays.append(self.zoomtool) self.scattertool = None self.scatter.overlays.append(ScatterInspectorOverlay(self.scatter, hover_color = "black", selection_color="black", selection_outline_color="red", selection_line_width=2)) self.colorbar = colorbar = ColorBar(index_mapper=LinearMapper(range=plot.color_mapper.range), color_mapper=plot.color_mapper.range, plot=plot, orientation='v', resizable='v', width = 30, padding = 5) colorbar.padding_top = plot.padding_top colorbar.padding_bottom = plot.padding_bottom colorbar._axis.title = 'Weights' self.plotcontainer = container = HPlotContainer(use_backbuffer=True) container.add(plot) container.add(colorbar) super(FitGui,self).__init__(**traits) self.on_trait_change(self._scale_change,'plot.value_scale,plot.index_scale') if weights is not None and len(weights)==2: self.weightsChanged() #update error bars
def clone_plot(clonetool, drop_position): # A little sketchy... canvas = clonetool.component.container.component.component # Create a new Plot object oldplot = clonetool.component newplot = Plot(oldplot.data) basic_traits = ["orientation", "default_origin", "bgcolor", "border_color", "border_width", "border_visible", "draw_layer", "unified_draw", "fit_components", "fill_padding", "visible", "aspect_ratio", "title"] for attr in basic_traits: setattr(newplot, attr, getattr(oldplot, attr)) # copy the ranges dst = newplot.range2d src = oldplot.range2d #for attr in ('_low_setting', '_low_value', '_high_setting', '_high_value'): # setattr(dst, attr, getattr(src, attr)) dst._xrange.sources = copy(src._xrange.sources) dst._yrange.sources = copy(src._yrange.sources) newplot.padding = oldplot.padding newplot.bounds = oldplot.bounds[:] newplot.resizable = "" newplot.position = drop_position newplot.datasources = copy(oldplot.datasources) for name, renderers in oldplot.plots.items(): newrenderers = [] for renderer in renderers: new_r = clone_renderer(renderer) new_r.index_mapper = LinearMapper(range=newplot.index_range) new_r.value_mapper = LinearMapper(range=newplot.value_range) new_r._layout_needed = True new_r.invalidate_draw() new_r.resizable = "hv" newrenderers.append(new_r) newplot.plots[name] = newrenderers #newplot.plots = copy(oldplot.plots) for name, renderers in newplot.plots.items(): newplot.add(*renderers) newplot.index_axis.title = oldplot.index_axis.title newplot.index_axis.unified_draw = True newplot.value_axis.title = oldplot.value_axis.title newplot.value_axis.unified_draw = True # Add new tools to the new plot newplot.tools.append(AxisTool(component=newplot, range_controller=canvas.range_controller)) # Add tools to the new plot pan_traits = ["drag_button", "constrain", "constrain_key", "constrain_direction", "speed"] zoom_traits = ["tool_mode", "always_on", "axis", "enable_wheel", "drag_button", "wheel_zoom_step", "enter_zoom_key", "exit_zoom_key", "pointer", "color", "alpha", "border_color", "border_size", "disable_on_complete", "minimum_screen_delta", "max_zoom_in_factor", "max_zoom_out_factor"] move_traits = ["drag_button", "end_drag_on_leave", "cancel_keys", "capture_mouse", "modifier_key"] if not MULTITOUCH: for tool in oldplot.tools: if isinstance(tool, PanTool): newtool = tool.clone_traits(pan_traits) newtool.component = newplot break else: newtool = PanTool(newplot) # Reconfigure the pan tool to always use the left mouse, because we will # put plot move on the right mouse button newtool.drag_button = "left" newplot.tools.append(newtool) for tool in oldplot.tools: if isinstance(tool, MoveTool): newtool = tool.clone_traits(move_traits) newtool.component = newplot break else: newtool = MoveTool(newplot, drag_button="right") newplot.tools.append(newtool) for tool in oldplot.tools: if isinstance(tool, ZoomTool): newtool = tool.clone_traits(zoom_traits) newtool.component = newplot break else: newtool = ZoomTool(newplot) newplot.tools.append(newtool) else: pz = MPPanZoom(newplot) #pz.pan.constrain = True #pz.pan.constrain_direction = "x" #pz.zoom.mode = "range" #pz.zoom.axis = "index" newplot.tools.append(MPPanZoom(newplot)) #newplot.tools.append(MTMoveTool( newplot._layout_needed = True clonetool.dest.add(newplot) newplot.invalidate_draw() newplot.request_redraw() canvas.request_redraw() return
def __init__(self): super(CyclesPlot, self).__init__() # Normally you'd pass in the data, but I'll hardwire things for this # one-off plot. srecs = read_time_series_from_csv("./biz_cycles2.csv", date_col=0, date_format="%Y-%m-%d") dt = srecs["Date"] # Industrial production compared with trend (plotted on value axis) iprod_vs_trend = srecs["Metric 1"] # Industrial production change in last 6 Months (plotted on index axis) iprod_delta = srecs["Metric 2"] self._dates = dt self._series1 = self._selected_s1 = iprod_delta self._series2 = self._selected_s2 = iprod_vs_trend end_x = np.array([self._selected_s1[-1]]) end_y = np.array([self._selected_s2[-1]]) plotdata = ArrayPlotData(x=self._series1, y=self._series2, dates=self._dates, selected_x=self._selected_s1, selected_y=self._selected_s2, endpoint_x=end_x, endpoint_y=end_y) cycles = Plot(plotdata, padding=20) cycles.plot(("x", "y"), type="line", color=(.2, .4, .5, .4)) cycles.plot(("selected_x", "selected_y"), type="line", marker="circle", line_width=3, color=(.2, .4, .5, .9)) cycles.plot(("endpoint_x", "endpoint_y"), type="scatter", marker_size=4, marker="circle", color=(.2, .4, .5, .2), outline_color=(.2, .4, .5, .6)) cycles.index_range = DataRange1D(low_setting=80., high_setting=120.) cycles.value_range = DataRange1D(low_setting=80., high_setting=120.) # dig down to use actual Plot object cyc_plot = cycles.components[0] # Add the labels in the quadrants cyc_plot.overlays.append( PlotLabel("\nSlowdown" + 40 * " " + "Expansion", component=cyc_plot, font="swiss 24", color=(.2, .4, .5, .6), overlay_position="inside top")) cyc_plot.overlays.append( PlotLabel("Downturn" + 40 * " " + "Recovery\n ", component=cyc_plot, font="swiss 24", color=(.2, .4, .5, .6), overlay_position="inside bottom")) timeline = Plot(plotdata, resizable='h', height=50, padding=20) timeline.plot(("dates", "x"), type="line", color=(.2, .4, .5, .8), name='x') timeline.plot(("dates", "y"), type="line", color=(.5, .4, .2, .8), name='y') # Snap on the tools zoomer = ZoomTool(timeline, drag_button="right", always_on=True, tool_mode="range", axis="index", max_zoom_out_factor=1.1) panner = PanTool(timeline, constrain=True, constrain_direction="x") # dig down to get Plot component I want x_plt = timeline.plots['x'][0] range_selection = RangeSelection(x_plt, left_button_selects=True) range_selection.on_trait_change(self.update_interval, 'selection') x_plt.tools.append(range_selection) x_plt.overlays.append(RangeSelectionOverlay(x_plt)) # Set the plot's bottom axis to use the Scales ticking system scale_sys = CalendarScaleSystem( fill_ratio=0.4, default_numlabels=5, default_numticks=10, ) tick_gen = ScalesTickGenerator(scale=scale_sys) bottom_axis = ScalesPlotAxis(timeline, orientation="bottom", tick_generator=tick_gen) # Hack to remove default axis - FIXME: how do I *replace* an axis? del (timeline.underlays[-2]) timeline.overlays.append(bottom_axis) container = GridContainer(padding=20, fill_padding=True, bgcolor="lightgray", use_backbuffer=True, shape=(2, 1), spacing=(30, 30)) # add a central "x" and "y" axis x_line = LineInspector(cyc_plot, is_listener=True, color="gray", width=2) y_line = LineInspector(cyc_plot, is_listener=True, color="gray", width=2, axis="value") cyc_plot.overlays.append(x_line) cyc_plot.overlays.append(y_line) cyc_plot.index.metadata["selections"] = 100.0 cyc_plot.value.metadata["selections"] = 100.0 container.add(cycles) container.add(timeline) container.title = "Business Cycles" self.plot = container
def add_plot(self, signal, sweep_point=None): ## waveform = signal.get_waveform() ## x = waveform.get_x()[-1][0].tolist() ## y = np.real(waveform.get_y()[0].tolist()) if sweep_point is None: sweep_point = signal.get_circuit()._sweep_set._points[0] trace = Trace(signal, self, self._next_color(), sweep_point) x_name = trace.index_label y_name = trace.label x = trace.get_indices() y = trace.get_values() if type(y[0]) == complex: y = [value.real for value in y] #print x_name, len(x) #print y_name, len(y) #print x #print y if self.firstplot: self.plotdata = ArrayPlotData() self.plotdata.set_data(x_name, x) self.plotdata.set_data(y_name, y) plot = Plot(self.plotdata) plot.padding = 1 plot.bgcolor = "white" plot.border_visible = True add_default_grids(plot) add_default_axes(plot) plot.tools.append(PanTool(plot)) # The ZoomTool tool is stateful and allows drawing a zoom # box to select a zoom region. zoom = CustomZoomTool(plot) plot.overlays.append(zoom) # The DragZoom tool just zooms in and out as the user drags # the mouse vertically. dragzoom = DragZoom(plot, drag_button="right") plot.tools.append(dragzoom) #~ # Add a legend in the upper right corner, and make it relocatable #~ self.legend = Legend(component=plot, padding=10, align="ur") #~ self.legend.tools.append(LegendTool(self.legend, drag_button="right")) #~ plot.overlays.append(self.legend) #~ self.legend.plots = {} self.firstplot = False self.container.add(plot) self.plot = plot else: self.plotdata.set_data(x_name, x) self.plotdata.set_data(y_name, y) #self.plot.plot(self.plotdata.list_data()) pl = self.plot.plot( (x_name, y_name), name=trace.label, type="line", color=trace.color, line_style=trace.line_style, line_width=trace.line_width, marker=trace.marker, marker_size=trace.marker_size, marker_color=trace.marker_color) self.legend.plots[trace.label] = pl self.Refresh()