def _plot_default(self): plotter = Plot(data=self.data) main_plot = plotter.plot(['x','y'])[0] self.configure_plot(main_plot, xlabel='') plotter2 = Plot(data=self.data) zoom_plot = plotter2.plot(['x','y'])[0] self.configure_plot(zoom_plot) plotter3 = Plot(data = self.data) events_plot = plotter3.plot(['x','y'])[0] self.configure_plot(events_plot) outer_container = VPlotContainer(padding=20, fill_padding=True, spacing=0, stack_order='top_to_bottom', bgcolor='lightgray', use_backbuffer=True) outer_container.add(main_plot) outer_container.add(zoom_plot) outer_container.add(events_plot) # FIXME: This is set to the windows bg color. Should get from the system. #outer_container.bgcolor = (236/255., 233/255., 216/255., 1.0) main_plot.controller = RangeSelection(main_plot) zoom_overlay = ZoomOverlay(source=main_plot, destination=zoom_plot) outer_container.overlays.append(zoom_overlay) return outer_container
def _create_plot_component(): # Create some x-y data series to plot x = linspace(-2.0, 10.0, 100) pd = ArrayPlotData(index=x) for i in range(5): pd.set_data("y" + str(i), jn(i, x)) # Create some line plots of some of the data plot1 = Plot(pd, padding=50) plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red") plot1.plot(("index", "y3"), name="j_3", color="blue") # Attach some tools to the plot plot1.tools.append(PanTool(plot1)) zoom = ZoomTool(component=plot1, tool_mode="box", always_on=False) plot1.overlays.append(zoom) # Add the scrollbar hscrollbar = PlotScrollBar(component=plot1, axis="index", resizable="h", height=15) plot1.padding_top = 0 hscrollbar.force_data_update() # Create a container and add our plots container = VPlotContainer() container.add(plot1) container.add(hscrollbar) return container
def _create_plot_component(): # Create some x-y data series to plot x = linspace(-2.0, 10.0, 100) pd = ArrayPlotData(index = x) for i in range(5): pd.set_data("y" + str(i), jn(i,x)) # Create some line plots of some of the data plot1 = Plot(pd, padding=50) plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red") plot1.plot(("index", "y3"), name="j_3", color="blue") # Attach some tools to the plot plot1.tools.append(PanTool(plot1)) zoom = ZoomTool(component=plot1, tool_mode="box", always_on=False) plot1.overlays.append(zoom) # Add the scrollbar hscrollbar = PlotScrollBar(component=plot1, axis="index", resizable="h", height=15) plot1.padding_top = 0 hscrollbar.force_data_update() # Create a container and add our plots container = VPlotContainer() container.add(plot1) container.add(hscrollbar) return container
def _create_plot_component(obj): # Spectrogram plot obj.data = fr.getDataSets(".chi") frequencies = obj.data[0][0] index = ArrayDataSource(data=frequencies) values = [obj.data[i][1] for i in xrange(len(obj.data))] print len(obj.data[1][1]) print len(obj.data) p = WaterfallRenderer( index=index, values=values, index_mapper=LinearMapper(range=DataRange1D(low=0, high=SPECTROGRAM_LENGTH)), value_mapper=LinearMapper(range=DataRange1D(low=0, high=SPECTROGRAM_LENGTH)), x2_mapper=LinearMapper(low_pos=0, high_pos=100, range=DataRange1D(low=10.0, high=101.0)), y2_mapper=LinearMapper(low_pos=0, high_pos=100, range=DataRange1D(low=0, high=600000)), ) spectrogram_plot = p obj.spectrogram_plot = p dummy = Plot() dummy.padding = 50 dummy.index_axis.mapper.range = p.index_mapper.range dummy.index_axis.title = "Frequency (hz)" dummy.add(p) c2 = VPlotContainer() c2.add(dummy) return c2
class WaveformDisplay(TwoDimensionalPlot): marker_height = 50 def __init__(self, parent, *args, **kwargs): TwoDimensionalPlot.__init__(self, parent, *args, **kwargs) self.padding_left = 50 self.title = 'Waveform' self.vplot_container = VPlotContainer(use_backbuffer=True) self.vplot_container.stack_order = 'top_to_bottom' self.vplot_container.add(self) @property def control(self): return Window(self.parent, component=self.vplot_container).control def add_marker(self, num, data): marker_plot = TwoDimensionalPlot(self, height=self.marker_height, resizable='h') marker_plot.padding_left = self.padding_left marker_plot.x_data = self.x_data marker_plot.y_data = data marker_plot.title = 'Marker {0}'.format(num) # Synchronize with waveform plot. marker_plot.index_range = self.index_range self.vplot_container.add(marker_plot)
def _plot_default(self): plotter = Plot(data=self.data) main_plot = plotter.plot(['x', 'y'])[0] self.configure_plot(main_plot, xlabel='') plotter2 = Plot(data=self.data) zoom_plot = plotter2.plot(['x', 'y'])[0] self.configure_plot(zoom_plot) outer_container = VPlotContainer(padding=20, fill_padding=True, spacing=0, stack_order='top_to_bottom', bgcolor='lightgray', use_backbuffer=True) outer_container.add(main_plot) outer_container.add(zoom_plot) # FIXME: This is set to the windows bg color. Should get from the system. #outer_container.bgcolor = (236/255., 233/255., 216/255., 1.0) main_plot.controller = RangeSelection(main_plot) zoom_overlay = ZoomOverlay(source=main_plot, destination=zoom_plot) outer_container.overlays.append(zoom_overlay) return outer_container
def create_vplot(self): ''' fill vplot container with 1 mini plot for range selection and N main plots ordered from to top to bottom by freq ''' vpc = VPlotContainer(bgcolor='lightgrey') if self.model.freq_choices: # create mini plot using the highest freq as background keys = self.model.freq_choices mini = self.create_hplot(key=keys[-1], mini=True) self.mini_hplot = mini vpc.add(mini) # create hplot containers for each freq and add to dict. # dictionary will be used to access these later to individually # address them to turn them on or off etc. # note these are added with lowest freq on bottom for freq in self.model.freq_choices: hpc = self.create_hplot(key=freq) self.hplot_dict[freq] = hpc vpc.add(hpc) # add tool to freeze line inspector cursor when in desired position vpc.tools.append(self.inspector_freeze_tool) self.vplot_container = vpc self.set_hplot_visibility(all=True) self.set_intensity_profile_visibility()
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) spec_renderer = obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red")[0] obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = list(obj.spectrum_plot.plots.values())[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0.0, float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = list(obj.time_plot.plots.values())[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot values = [zeros(NUM_SAMPLES/2) for i in range(SPECTROGRAM_LENGTH)] p = WaterfallRenderer(index = spec_renderer.index, values = values, index_mapper = LinearMapper(range = obj.spectrum_plot.index_mapper.range), value_mapper = LinearMapper(range = DataRange1D(low=0, high=SPECTROGRAM_LENGTH)), y2_mapper = LinearMapper(low_pos=0, high_pos=8, range=DataRange1D(low=0, high=15)), ) spectrogram_plot = p obj.spectrogram_plot = p dummy = Plot() dummy.padding = 50 dummy.index_axis.mapper.range = p.index_mapper.range dummy.index_axis.title = "Frequency (hz)" dummy.add(p) container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) c2 = VPlotContainer() c2.add(dummy) c2.add(container) return c2
def test_halign(self): container = VPlotContainer(bounds=[200, 300], halign="center") comp1 = StaticPlotComponent([100, 200]) container.add(comp1) container.do_layout() self.assertEqual(comp1.position, [50, 0]) container.halign = "right" container.do_layout(force=True) self.assertEqual(comp1.position, [100, 0]) return
def test_halign(self): container = VPlotContainer(bounds=[200,300], halign="center") comp1 = StaticPlotComponent([100,200]) container.add(comp1) container.do_layout() self.assertEqual(comp1.position, [50,0]) container.halign="right" container.do_layout(force=True) self.assertEqual(comp1.position, [100,0]) return
def _create_plot_component_vertical(signals=Array, use_downsampling=False): # container = HPlotContainer(resizable = "hv", bgcolor="lightgray", # fill_padding=True, padding = 10) container = VPlotContainer(resizable="hv", bgcolor="lightgray", fill_padding=True, padding=50) nSignal, nSample = np.shape(signals) time = arange(nSample) value_range = None plots = {} for i in range(nSignal): plot = create_line_plot( (time, signals[i]), color=tuple(COLOR_PALETTE[i % len(COLOR_PALETTE)]), width=1.0, # orientation="v") orientation="h") plot.origin_axis_visible = True # plot.origin = "top left" plot.padding_left = 10 plot.padding_right = 10 plot.border_visible = False plot.bgcolor = "white" if value_range is None: value_range = plot.value_mapper.range else: plot.value_range = value_range value_range.add(plot.value) container.add(plot) plots["Corr fun %d" % i] = plot # Add a legend in the upper right corner, and make it relocatable legend = Legend(component=plot, padding=10, align="ur") legend.tools.append(LegendTool(legend, drag_button="right")) plot.overlays.append(legend) legend.plots = plots # container.padding_top = 50 container.overlays.append( PlotLabel("Correlation function", component=container, font="swiss 16", overlay_position="top")) # selection_overlay = RangeSelectionOverlay(component=plot) # plot.tools.append(RangeSelection(plot)) zoom = ZoomTool(plot, tool_mode="box", always_on=False) # plot.overlays.append(selection_overlay) plot.overlays.append(zoom) return container
class ChacoReporter(StateDataReporter, HasTraits): plots = Instance(VPlotContainer) labels = List traits_view = View( Group(Item('plots', editor=ComponentEditor(), show_label=False)), width=800, height=600, resizable=True, title='OpenMM') def construct_plots(self): """Build the Chaco Plots. This will be run on the first report """ self.labels = super(ChacoReporter, self)._headers() self.plots = VPlotContainer(resizable="hv", bgcolor="lightgray", fill_padding=True, padding=10) # this looks cryptic, but it is equivalent to # ArrayPlotData(a=[], b=[], c=[]) # if the keys are a,b,c. This just does it for all of the keys. self.plotdata = ArrayPlotData(**dict(zip(self.labels, [[]]*len(self.labels)))) # figure out which key will be the x axis x = None x_labels = ['Time (ps)', 'Step'] for possible_x in x_labels: if possible_x in self.labels: x = possible_x break if x is None: raise ValueError('The reporter published neither the step nor time' 'count, so I don\'t know what to plot on the x-axis!') colors = itertools.cycle(['blue', 'green', 'silver', 'pink', 'lightblue', 'red', 'darkgray', 'lightgreen']) for y in set(self.labels).difference(x_labels): self.plots.add(chaco_scatter(self.plotdata, x_name=x, y_name=y, color=colors.next())) def _constructReportValues(self, simulation, state): values = super(ChacoReporter, self)._constructReportValues(simulation, state) for i, label in enumerate(self.labels): current = self.plotdata.get_data(label) self.plotdata.set_data(label, np.r_[current, float(values[i])]) return values def report(self, simulation, state): if not self._hasInitialized: self.construct_plots() super(ChacoReporter, self).report(simulation, state)
def test_stack_nonresize(self): container = VPlotContainer(bounds=[100,300]) comp1 = StaticPlotComponent([70,100]) comp2 = StaticPlotComponent([80,90]) comp3 = StaticPlotComponent([90,80]) container.add(comp1, comp2, comp3) container.do_layout() self.assert_tuple(container.get_preferred_size(), (90, 270)) self.assert_tuple(container.bounds, (100,300)) self.assert_tuple(comp1.position, (0,0)) self.assert_tuple(comp2.position, (0,100)) self.assert_tuple(comp3.position, (0,190)) return
def test_stack_nonresize(self): container = VPlotContainer(bounds=[100, 300]) comp1 = StaticPlotComponent([70, 100]) comp2 = StaticPlotComponent([80, 90]) comp3 = StaticPlotComponent([90, 80]) container.add(comp1, comp2, comp3) container.do_layout() self.assert_tuple(container.get_preferred_size(), (90, 270)) self.assert_tuple(container.bounds, (100, 300)) self.assert_tuple(comp1.position, (0, 0)) self.assert_tuple(comp2.position, (0, 100)) self.assert_tuple(comp3.position, (0, 190)) return
def normal_left_dclick(self, event): plot = Plot(self.data) for data, kw in self.command_queue: plot.plot(data, **kw) plot.title = self.title plot.title = self.title container = VPlotContainer(bgcolor=WindowColor) container.add(plot) plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) window = PlotWindow(plot=container) window.edit_traits(kind='live', parent=event.window.control)
def _create_plot_component_vertical(signals=Array, use_downsampling=False): # container = HPlotContainer(resizable = "hv", bgcolor="lightgray", # fill_padding=True, padding = 10) container = VPlotContainer(resizable="hv", bgcolor="lightgray", fill_padding=True, padding=50) nSignal, nSample = np.shape(signals) time = arange(nSample) value_range = None plots = {} for i in range(nSignal): plot = create_line_plot((time, signals[i]), color=tuple(COLOR_PALETTE[i % len(COLOR_PALETTE)]), width=1.0, # orientation="v") orientation="h") plot.origin_axis_visible = True # plot.origin = "top left" plot.padding_left = 10 plot.padding_right = 10 plot.border_visible = False plot.bgcolor = "white" if value_range is None: value_range = plot.value_mapper.range else: plot.value_range = value_range value_range.add(plot.value) container.add(plot) plots["Corr fun %d" % i] = plot # Add a legend in the upper right corner, and make it relocatable legend = Legend(component=plot, padding=10, align="ur") legend.tools.append(LegendTool(legend, drag_button="right")) plot.overlays.append(legend) legend.plots = plots # container.padding_top = 50 container.overlays.append(PlotLabel("Correlation function", component=container, font="swiss 16", overlay_position="top")) # selection_overlay = RangeSelectionOverlay(component=plot) # plot.tools.append(RangeSelection(plot)) zoom = ZoomTool(plot, tool_mode="box", always_on=False) # plot.overlays.append(selection_overlay) plot.overlays.append(zoom) return container
def _composite_plot_default(self): line_plot = Plot(self.plotdata) line_plot.plot(('x', 'y'), type='line', color='blue') img_plot = Plot(self.plotdata) img_plot.img_plot("zdata", xbounds='x_range', ybounds='y_range', colormap=jet) cp = VPlotContainer() cp.add(img_plot) cp.add(line_plot) return cp
def _container_default(self): plot = Plot(self.dataset) plot.plot( ('dates', self.data_provider.code), type='line') # Add tools plot.tools.append(ZoomTool(plot)) plot.tools.append(PanTool(plot)) # Set the plot's bottom axis to use the Scales ticking system ticker = ScalesTickGenerator(scale=CalendarScaleSystem()) plot.x_axis.tick_generator = ticker container = VPlotContainer() container.add(plot) return container
def test_stack_one_resize(self): "Checks stacking with 1 resizable component thrown in" container = VPlotContainer(bounds=[100, 300]) comp1 = StaticPlotComponent([70, 100]) comp2 = StaticPlotComponent([80, 90]) comp3 = StaticPlotComponent([90, 80], resizable='hv') comp4 = StaticPlotComponent([50, 40]) container.add(comp1, comp2, comp3, comp4) container.do_layout() self.assert_tuple(container.get_preferred_size(), (80, 230)) self.assert_tuple(container.bounds, (100, 300)) self.assert_tuple(comp1.position, (0, 0)) self.assert_tuple(comp2.position, (0, 100)) self.assert_tuple(comp3.position, (0, 190)) self.assert_tuple(comp4.position, (0, 260)) return
def _container_default(self): plot = Plot(self.dataset) plot.plot(('dates', self.data_provider.code), type='line') # Add tools plot.tools.append(ZoomTool(plot)) plot.tools.append(PanTool(plot)) # Set the plot's bottom axis to use the Scales ticking system ticker = ScalesTickGenerator(scale=CalendarScaleSystem()) plot.x_axis.tick_generator = ticker container = VPlotContainer() container.add(plot) return container
def test_stack_one_resize(self): "Checks stacking with 1 resizable component thrown in" container = VPlotContainer(bounds=[100,300]) comp1 = StaticPlotComponent([70,100]) comp2 = StaticPlotComponent([80,90]) comp3 = StaticPlotComponent([90,80], resizable='hv') comp4 = StaticPlotComponent([50,40]) container.add(comp1, comp2, comp3, comp4) container.do_layout() self.assert_tuple(container.get_preferred_size(), (80,230)) self.assert_tuple(container.bounds, (100,300)) self.assert_tuple(comp1.position, (0,0)) self.assert_tuple(comp2.position, (0,100)) self.assert_tuple(comp3.position, (0,190)) self.assert_tuple(comp4.position, (0,260)) return
def _container_default(self): #image_container = OverlayPlotContainer(padding=20, # use_backbuffer=True, # unified_draw=True) #image_container.add(self.plot) container = HPlotContainer(padding=40, fill_padding=True, bgcolor="white", use_backbuffer=False) inner_cont = VPlotContainer(padding=0, use_backbuffer=True) # container = HPlotContainer(bgcolor = "white", use_backbuffer=False) # inner_cont = VPlotContainer(use_backbuffer=True) inner_cont.add(self.h_plot) inner_cont.add(self.plot) container.add(inner_cont) container.add(self.v_plot) return container
def _create_window(self): # Create the data and datasource objects # In order for the date axis to work, the index data points need to # be in units of seconds since the epoch. This is because we are using # the CalendarScaleSystem, whose formatters interpret the numerical values # as seconds since the epoch. numpoints = 500 index = create_dates(numpoints) returns = random.lognormal(0.01, 0.1, size=numpoints) price = 100.0 * cumprod(returns) volume = abs(random.normal(1000.0, 1500.0, size=numpoints) + 2000.0) time_ds = ArrayDataSource(index) vol_ds = ArrayDataSource(volume, sort_order="none") price_ds = ArrayDataSource(price, sort_order="none") # Create the price plots price_plot, mini_plot = self._create_price_plots(time_ds, price_ds) price_plot.index_mapper.domain_limits = (index[0], index[-1]) self.price_plot = price_plot self.mini_plot = mini_plot # Create the volume plot vol_plot = self._create_vol_plot(time_ds, vol_ds) vol_plot.index_mapper.domain_limits = (index[0], index[-1]) # Set the plot's bottom axis to use the Scales ticking system ticker = ScalesTickGenerator(scale=CalendarScaleSystem()) for plot in price_plot, mini_plot, vol_plot: bottom_axis = PlotAxis(plot, orientation="bottom", tick_generator=ticker) plot.overlays.append(bottom_axis) plot.overlays.append(PlotAxis(plot, orientation="left")) hgrid, vgrid = add_default_grids(plot) vgrid.tick_generator = bottom_axis.tick_generator container = VPlotContainer(bgcolor="lightgray", spacing=40, padding=50, fill_padding=False) container.add(mini_plot, vol_plot, price_plot) return Window(self, -1, component=container)
def test_fit_components(self): container = VPlotContainer(bounds=[200,300], resizable="v", fit_components="v") comp1 = StaticPlotComponent([50,100], padding=5) comp2 = StaticPlotComponent([50,120], padding=5) container.add(comp1) container.add(comp2) self.assert_tuple(container.get_preferred_size(), (200,240)) # The container should not change its size as a result of its fit_components # being set. self.assert_tuple(container.bounds, (200,300)) container.bounds = container.get_preferred_size() container.do_layout() container.padding = 8 self.assert_tuple(container.get_preferred_size(), (216,256)) container.do_layout() self.assert_tuple(comp1.outer_position, (0,0)) self.assert_tuple(comp2.outer_position, (0,110))
def _create_window(self): # Create the data and datasource objects # In order for the date axis to work, the index data points need to # be in units of seconds since the epoch. This is because we are using # the CalendarScaleSystem, whose formatters interpret the numerical values # as seconds since the epoch. numpoints = 500 index = create_dates(numpoints) returns = random.lognormal(0.01, 0.1, size=numpoints) price = 100.0 * cumprod(returns) volume = abs(random.normal(1000.0, 1500.0, size=numpoints) + 2000.0) time_ds = ArrayDataSource(index) vol_ds = ArrayDataSource(volume, sort_order="none") price_ds = ArrayDataSource(price, sort_order="none") # Create the price plots price_plot, mini_plot = self._create_price_plots(time_ds, price_ds) price_plot.index_mapper.domain_limits = (index[0], index[-1]) self.price_plot = price_plot self.mini_plot = mini_plot # Create the volume plot vol_plot = self._create_vol_plot(time_ds, vol_ds) vol_plot.index_mapper.domain_limits = (index[0], index[-1]) # Set the plot's bottom axis to use the Scales ticking system ticker = ScalesTickGenerator(scale=CalendarScaleSystem()) for plot in price_plot, mini_plot, vol_plot: bottom_axis = PlotAxis(plot, orientation="bottom", tick_generator = ticker) plot.overlays.append(bottom_axis) plot.overlays.append(PlotAxis(plot, orientation="left")) hgrid, vgrid = add_default_grids(plot) vgrid.tick_generator = bottom_axis.tick_generator container = VPlotContainer(bgcolor = "lightgray", spacing = 40, padding = 50, fill_padding=False) container.add(mini_plot, vol_plot, price_plot) return Window(self, -1, component=container)
def _component_default(self): padding = (25, 5, 5, 25) image_plot = Plot(self.plot_data, padding=padding) image_plot.img_plot("image", origin="top left", xbounds=(-pi, pi), ybounds=(-pi, pi), colormap=gray) blurred_image_plot = Plot(self.plot_data, padding=padding) blurred_image_plot.img_plot("blurred_image", origin="top left", xbounds=(-pi, pi), ybounds=(-pi, pi), colormap=gray) container = VPlotContainer() container.add(blurred_image_plot) container.add(image_plot) return container
def test_fit_components(self): container = VPlotContainer(bounds=[200, 300], resizable="v", fit_components="v") comp1 = StaticPlotComponent([50, 100], padding=5) comp2 = StaticPlotComponent([50, 120], padding=5) container.add(comp1) container.add(comp2) self.assert_tuple(container.get_preferred_size(), (200, 240)) # The container should not change its size as a result of its fit_components # being set. self.assert_tuple(container.bounds, (200, 300)) container.bounds = container.get_preferred_size() container.do_layout() container.padding = 8 self.assert_tuple(container.get_preferred_size(), (216, 256)) container.do_layout() self.assert_tuple(comp1.outer_position, (0, 0)) self.assert_tuple(comp2.outer_position, (0, 110))
def createImagePanel(self): '''Creates the Image Panel Creates the image panel that contains the 2D image, colorbarm histogram, and 1D slice. ''' cont = VPlotContainer(stack_order = 'top_to_bottom', bgcolor = 'transparent', use_backbuffer=True) imageplot = getattr(self.rawviewer, 'imageplot') colorbar = getattr(self.rawviewer.display, 'colorbar') histogram = getattr(self.rawviewer, 'histogram') plot1d = getattr(self.rawviewer, 'plot1d') imgcont = HPlotContainer(imageplot, colorbar, bgcolor = 'transparent', spacing = 20.0) cont.add(imgcont) cont.add(histogram) cont.add(plot1d) self.imagepanel = cont self.imagepanel.get_preferred_size() self.imagepanel.invalidate_draw() return
def _composite_plot_default(self): x_line = np.linspace(-14, 14, 100) y_line = np.sin(x_line) * x_line**3 x = np.linspace(0, 10, 51) y = np.linspace(0, 5, 51) X, Y = np.meshgrid(x, y) z = np.exp(-(X**2 + Y**2) / 100) plotdata = ArrayPlotData(x=x_line, y=y_line, zdata=z[:-1, :-1]) line_plot = Plot(plotdata) line_plot.plot(('x', 'y'), type='line', color='blue') img_plot = Plot(plotdata) img_plot.img_plot("zdata", xbounds=x, ybounds=y, colormap=jet) cp = VPlotContainer() cp.add(img_plot) cp.add(line_plot) return cp
def _stackedhist_default(self): plot = Plot(self.stackedhist_data, padding=(25, 0, 5, 20)) plot_selected = plot.plot(('index', 'selected'), type='bar', bar_width=1, fill_color='red', line_color='red') plot_parkinson = plot.plot(('index', 'positives'), type='bar', bar_width=0.5, fill_color='yellow', line_color='yellow') plot_control = plot.plot(('index', 'negatives'), name="select", type='bar', bar_width=0.5, fill_color='blue', line_color='blue') # set the plot's value low range to 0, otherwise it will pad too much plot.value_range = DataRange1D(low_settings=0) legend = Legend(component=plot, padding=5, align='ur', plots={'Control': plot_control, 'Parkinson': plot_parkinson}) plot.overlays.append(legend) #return plot zoomplot = Plot(self.stackedhist_data, padding=(25, 0, 5, 20)) zoomplot_selected = zoomplot.plot(('index', 'selected'), type='bar', bar_width=1, fill_color='red', line_color='red') zoomplot_parkinson = zoomplot.plot(('index', 'positives'), type='bar', bar_width=0.5, fill_color='yellow', line_color='yellow') zoomplot_control = zoomplot.plot(('index', 'negatives'), type='bar', bar_width=0.5, fill_color='blue', line_color='blue') zoomplot.value_range = DataRange1D(low_settings=0) zoomplot.index_axis.title = "Class count / patch" outer_container = VPlotContainer(padding=20, fill_padding=True, spacing=0, stack_order='top_to_bottom', bgcolor='lightgray', use_backbuffer=True) plot.index = plot_control[0].index outer_container.add(plot) outer_container.add(zoomplot) plot.controller = RangeSelection(plot) zoom_overlay = ZoomOverlay(source=plot, destination=zoomplot) outer_container.overlays.append(zoom_overlay) return outer_container
class ExpressionContextDemo(HasTraits): code = Code() execute = Button() plots = Instance(PlotComponent) value_expression = Str('') index_expression = Str('') view_expression = Button() data_context = Instance(DataContext) expression_context = Instance(ExpressionContext) traits_view = View('code', 'execute', Item('plots', editor=ComponentEditor()), 'value_expression', 'index_expression', Item('view_expression', show_label=False), resizable=True) def __init__(self): self.data_context = DataContext() self.expression_context = ExpressionContext(self.data_context) self.plots = VPlotContainer() return def _view_expression_fired(self): context_adapter = PlotDataContextAdapter(context=self.expression_context) plot = Plot(context_adapter) plot.plot((self.index_expression, self.value_expression)) self.plots.add(plot) self.plots.request_redraw() return def _execute_fired(self): exec_(self.code, {}, self.data_context) return
class ExpressionContextDemo(HasTraits): code = Code() execute = Button() plots = Instance(PlotComponent) value_expression = Str('') index_expression = Str('') view_expression = Button() data_context = Instance(DataContext) expression_context = Instance(ExpressionContext) traits_view = View('code', 'execute', Item('plots', editor=ComponentEditor()), 'value_expression', 'index_expression', Item('view_expression', show_label=False), resizable=True) def __init__(self): self.data_context = DataContext() self.expression_context = ExpressionContext(self.data_context) self.plots = VPlotContainer() return def _view_expression_fired(self): context_adapter = PlotDataContextAdapter( context=self.expression_context) plot = Plot(context_adapter) plot.plot((self.index_expression, self.value_expression)) self.plots.add(plot) self.plots.request_redraw() return def _execute_fired(self): exec(self.code, {}, self.data_context) return
def _image_default(self): container = VPlotContainer() soln_plot = Plot(self.soln_data) soln_plot.plot(("x", "y"), type='bar', fill_color='green', bar_width=0.8) container.add(soln_plot) galaxy_plot = Plot(self.image_data) galaxy_plot.img_plot('im') container.add(galaxy_plot) container.add(self.cropped_image) return container
def createImagePanel(self): '''Creates the image panel and fills it with the associated plots. The plots included are the image plot, histogram, and 1D plot. Data can be set for these plots without changing the Plot objects. ''' cont = VPlotContainer(stack_order = 'top_to_bottom', bgcolor = 'transparent', use_backbuffer=True) imageplot = getattr(self.process, 'imageplot') colorbar = getattr(self.process.display, 'colorbar') histogram = getattr(self.process, 'histogram') plot1d = getattr(self.process, 'plot1d') imgcont = HPlotContainer(imageplot, colorbar, bgcolor = 'transparent', spacing = 20.0) cont.add(imgcont) cont.add(histogram) cont.add(plot1d) self.imagepanel = cont self.imagepanel.get_preferred_size() self.imagepanel.invalidate_draw() return
class TriangleWave(HasTraits): # 指定三角波的最窄和最宽范围,由于Range似乎不能将常数和traits名混用 # 所以定义这两个不变的trait属性 low = Float(0.02) hi = Float(1.0) # 三角波形的宽度 wave_width = Range("low", "hi", 0.5) # 三角波的顶点C的x轴坐标 length_c = Range("low", "wave_width", 0.5) # 三角波的定点的y轴坐标 height_c = Float(1.0) # FFT计算所使用的取样点数,这里用一个Enum类型的属性以供用户从列表中选择 fftsize = Enum( [(2**x) for x in range(6, 12)]) # FFT频谱图的x轴上限值 fft_graph_up_limit = Range(0, 400, 20) # 用于显示FFT的结果 peak_list = Str # 采用多少个频率合成三角波 N = Range(1, 40, 4) # 保存绘图数据的对象 plot_data = Instance(AbstractPlotData) # 绘制波形图的容器 plot_wave = Instance(Component) # 绘制FFT频谱图的容器 plot_fft = Instance(Component) # 包括两个绘图的容器 container = Instance(Component) # 设置用户界面的视图, 注意一定要指定窗口的大小,这样绘图容器才能正常初始化 view = View( HSplit( VSplit( VGroup( Item("wave_width", editor = scrubber, label=u"波形宽度"), Item("length_c", editor = scrubber, label=u"最高点x坐标"), Item("height_c", editor = scrubber, label=u"最高点y坐标"), Item("fft_graph_up_limit", editor = scrubber, label=u"频谱图范围"), Item("fftsize", label=u"FFT点数"), Item("N", label=u"合成波频率数") ), Item("peak_list", style="custom", show_label=False, width=100, height=250) ), VGroup( Item("container", editor=ComponentEditor(size=(600,300)), show_label = False), orientation = "vertical" ) ), resizable = True, width = 800, height = 600, title = u"三角波FFT演示" ) # 创建绘图的辅助函数,创建波形图和频谱图有很多类似的地方,因此单独用一个函数以 # 减少重复代码 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 __init__(self): # 首先需要调用父类的初始化函数 super(TriangleWave, self).__init__() # 创建绘图数据集,暂时没有数据因此都赋值为空,只是创建几个名字,以供Plot引用 self.plot_data = ArrayPlotData(x=[], y=[], f=[], p=[], x2=[], y2=[]) # 创建一个垂直排列的绘图容器,它将频谱图和波形图上下排列 self.container = VPlotContainer() # 创建波形图,波形图绘制两条曲线: 原始波形(x,y)和合成波形(x2,y2) self.plot_wave = self._create_plot(("x","y"), "Triangle Wave") self.plot_wave.plot(("x2","y2"), color="red") # 创建频谱图,使用数据集中的f和p self.plot_fft = self._create_plot(("f","p"), "FFT", type="scatter") # 将两个绘图容器添加到垂直容器中 self.container.add( self.plot_wave ) self.container.add( self.plot_fft ) # 设置 self.plot_wave.x_axis.title = "Samples" self.plot_fft.x_axis.title = "Frequency pins" self.plot_fft.y_axis.title = "(dB)" # 改变fftsize为1024,因为Enum的默认缺省值为枚举列表中的第一个值 self.fftsize = 1024 # FFT频谱图的x轴上限值的改变事件处理函数,将最新的值赋值给频谱图的响应属性 def _fft_graph_up_limit_changed(self): self.plot_fft.x_axis.mapper.range.high = self.fft_graph_up_limit def _N_changed(self): self.plot_sin_combine() # 多个trait属性的改变事件处理函数相同时,可以用@on_trait_change指定 @on_trait_change("wave_width, length_c, height_c, fftsize") def update_plot(self): # 计算三角波 global y_data x_data = np.arange(0, 1.0, 1.0/self.fftsize) func = self.triangle_func() # 将func函数的返回值强制转换成float64 y_data = np.cast["float64"](func(x_data)) # 计算频谱 fft_parameters = np.fft.fft(y_data) / len(y_data) # 计算各个频率的振幅 fft_data = np.clip(20*np.log10(np.abs(fft_parameters))[:self.fftsize/2+1], -120, 120) # 将计算的结果写进数据集 self.plot_data.set_data("x", np.arange(0, self.fftsize)) # x坐标为取样点 self.plot_data.set_data("y", y_data) self.plot_data.set_data("f", np.arange(0, len(fft_data))) # x坐标为频率编号 self.plot_data.set_data("p", fft_data) # 合成波的x坐标为取样点,显示2个周期 self.plot_data.set_data("x2", np.arange(0, 2*self.fftsize)) # 更新频谱图x轴上限 self._fft_graph_up_limit_changed() # 将振幅大于-80dB的频率输出 peak_index = (fft_data > -80) peak_value = fft_data[peak_index][:20] result = [] for f, v in zip(np.flatnonzero(peak_index), peak_value): result.append("%s : %s" %(f, v) ) self.peak_list = "\n".join(result) # 保存现在的fft计算结果,并计算正弦合成波 self.fft_parameters = fft_parameters self.plot_sin_combine() # 计算正弦合成波,计算2个周期 def plot_sin_combine(self): index, data = fft_combine(self.fft_parameters, self.N, 2) self.plot_data.set_data("y2", data) # 返回一个ufunc计算指定参数的三角波 def triangle_func(self): c = self.wave_width c0 = self.length_c hc = self.height_c def trifunc(x): x = x - int(x) # 三角波的周期为1,因此只取x坐标的小数部分进行计算 if x >= c: r = 0.0 elif x < c0: r = x / c0 * hc else: r = (c-x) / (c-c0) * hc return r # 用trifunc函数创建一个ufunc函数,可以直接对数组进行计算, 不过通过此函数 # 计算得到的是一个Object数组,需要进行类型转换 return np.frompyfunc(trifunc, 1, 1)
def _get_plot_vertical(self): if self.data is None or len(self.data.shape) == 1: return container = VPlotContainer(resizable="v", fill_padding=True, padding=30, stack_order="top_to_bottom", bgcolor="transparent", spacing=9) numpoints = self.data.shape[1] if self.scale_type == 'Time': index = self._create_dates(numpoints, start=self.first_day) else: index = range(numpoints) time_ds = ArrayDataSource(index) xmapper = LinearMapper(range=DataRange1D(time_ds)) corr_mapper = None for (m, cDx) in enumerate(self.data): corr_ds = ArrayDataSource(cDx, sort_order="none") corr_mapper = LinearMapper(range=DataRange1D(corr_ds)) if corr_mapper.range.low < self.y_low: self.y_low = corr_mapper.range.low if corr_mapper.range.high > self.y_high: self.y_high = corr_mapper.range.high corr_plot = LinePlot(index=time_ds, value=corr_ds, index_mapper=xmapper, value_mapper=corr_mapper, edge_color="blue", face_color="paleturquoise", bgcolor="white", border_visible=True, padding_left=25) ###### Y axis ##################################################### if self.y_lbl_type == 'Corr': vtitle = ("%d" % (m + 1)) + u"\u00B0" + " t_win" elif self.y_lbl_type == 'Single': vtitle = "" # One label for all the axis elif self.y_lbl_type == 'Custom' and \ len(self.y_labels) == self.data.shape[0] and \ self.y_labels[m] is not None: # a new value in the list defaults to None so raise an error before # the operator ends inputing it. vtitle = self.y_labels[m] else: vtitle = "" left = PlotAxis( orientation='left', title=vtitle, title_font="modern 12", #title_spacing=0, tick_label_font="modern 8", tick_visible=True, small_axis_style=True, axis_line_visible=False, ensure_labels_bounded=True, #tick_label_color="transparent", mapper=corr_mapper, component=corr_plot) corr_plot.overlays.append(left) ###### X axis ##################################################### if m != (self.data.shape[0] - 1): if self.scale_type == 'Time': # Set the plot's bottom axis to use the Scales ticking system bottom_axis = PlotAxis( corr_plot, orientation="bottom", tick_label_color="transparent", # mapper=xmapper, tick_generator=ScalesTickGenerator( scale=CalendarScaleSystem())) else: bottom_axis = PlotAxis(orientation='bottom', title="", tick_label_color="transparent", tick_visible=True, small_axis_style=True, axis_line_visible=False, component=corr_plot) else: if self.scale_type == 'Time': # Just the last axis shows tick_labels bottom_axis = PlotAxis(corr_plot, orientation="bottom", title=self.x_lbl, tick_generator=ScalesTickGenerator( scale=CalendarScaleSystem())) else: bottom_axis = PlotAxis(orientation='bottom', title=self.x_lbl, title_font="modern 12", tick_visible=True, small_axis_style=True, axis_line_visible=False, component=corr_plot) corr_plot.overlays.append(bottom_axis) _, vgrid = add_default_grids(corr_plot) vgrid.tick_generator = bottom_axis.tick_generator corr_plot.tools.append( PanTool(corr_plot, constrain=True, constrain_direction="x")) corr_plot.overlays.append( ZoomTool( corr_plot, drag_button="right", always_on=True, tool_mode="box", #axis="index", max_zoom_out_factor=10.0, )) container.add(corr_plot) for component in container.components: component.y_mapper.range.set_bounds(self.y_low, self.y_high) container.overlays.append( PlotLabel(self.p_title, component=container, overlay_position="outside top", font="modern 16")) if self.y_lbl_type == 'Single': container.overlays.append( PlotLabel(self.y_lbl, component=container, angle=90.0, overlay_position="outside left", font="modern 12")) container.padding_bottom = 50 return container
def create_plot(self): # Create the mapper, etc self._image_index = GridDataSource(array([]), array([]), sort_order=("ascending","ascending")) image_index_range = DataRange2D(self._image_index) self._image_index.on_trait_change(self._metadata_changed, "metadata_changed") self._image_value = ImageData(data=array([]), value_depth=1) image_value_range = DataRange1D(self._image_value) # Create the contour plots self.polyplot = ContourPolyPlot(index=self._image_index, value=self._image_value, index_mapper=GridMapper(range= image_index_range), color_mapper=\ self._cmap(image_value_range), levels=self.num_levels) self.lineplot = ContourLinePlot(index=self._image_index, value=self._image_value, index_mapper=GridMapper(range= self.polyplot.index_mapper.range), levels=self.num_levels) # Add a left axis to the plot left = PlotAxis(orientation='left', title= "y", mapper=self.polyplot.index_mapper._ymapper, component=self.polyplot) self.polyplot.overlays.append(left) # Add a bottom axis to the plot bottom = PlotAxis(orientation='bottom', title= "x", mapper=self.polyplot.index_mapper._xmapper, component=self.polyplot) self.polyplot.overlays.append(bottom) # Add some tools to the plot self.polyplot.tools.append(PanTool(self.polyplot, constrain_key="shift")) self.polyplot.overlays.append(ZoomTool(component=self.polyplot, tool_mode="box", always_on=False)) self.polyplot.overlays.append(LineInspector(component=self.polyplot, axis='index_x', inspect_mode="indexed", write_metadata=True, is_listener=True, color="white")) self.polyplot.overlays.append(LineInspector(component=self.polyplot, axis='index_y', inspect_mode="indexed", write_metadata=True, color="white", is_listener=True)) # Add these two plots to one container contour_container = OverlayPlotContainer(padding=20, use_backbuffer=True, unified_draw=True) contour_container.add(self.polyplot) contour_container.add(self.lineplot) # Create a colorbar cbar_index_mapper = LinearMapper(range=image_value_range) self.colorbar = ColorBar(index_mapper=cbar_index_mapper, plot=self.polyplot, padding_top=self.polyplot.padding_top, padding_bottom=self.polyplot.padding_bottom, padding_right=40, resizable='v', width=30) self.pd = ArrayPlotData(line_index = array([]), line_value = array([]), scatter_index = array([]), scatter_value = array([]), scatter_color = array([])) self.cross_plot = Plot(self.pd, resizable="h") self.cross_plot.height = 100 self.cross_plot.padding = 20 self.cross_plot.plot(("line_index", "line_value"), line_style="dot") self.cross_plot.plot(("scatter_index","scatter_value","scatter_color"), type="cmap_scatter", name="dot", color_mapper=self._cmap(image_value_range), marker="circle", marker_size=8) self.cross_plot.index_range = self.polyplot.index_range.x_range self.pd.set_data("line_index2", array([])) self.pd.set_data("line_value2", array([])) self.pd.set_data("scatter_index2", array([])) self.pd.set_data("scatter_value2", array([])) self.pd.set_data("scatter_color2", array([])) self.cross_plot2 = Plot(self.pd, width = 140, orientation="v", resizable="v", padding=20, padding_bottom=160) self.cross_plot2.plot(("line_index2", "line_value2"), line_style="dot") self.cross_plot2.plot(("scatter_index2", "scatter_value2", "scatter_color2"), type="cmap_scatter", name="dot", color_mapper=self._cmap(image_value_range), marker="circle", marker_size=8) self.cross_plot2.index_range = self.polyplot.index_range.y_range # Create a container and add components self.container = HPlotContainer(padding=40, fill_padding=True, bgcolor = "white", use_backbuffer=False) inner_cont = VPlotContainer(padding=0, use_backbuffer=True) inner_cont.add(self.cross_plot) inner_cont.add(contour_container) self.container.add(self.colorbar) self.container.add(inner_cont) self.container.add(self.cross_plot2)
def create_plot(self): # Create the mapper, etc self._image_index = GridDataSource(array([]), array([]), sort_order=("ascending","ascending")) image_index_range = DataRange2D(self._image_index) self._image_index.on_trait_change(self._metadata_changed, "metadata_changed") self._image_value = ImageData(data=array([]), value_depth=1) image_value_range = DataRange1D(self._image_value) # Create the contour plots self.polyplot = ContourPolyPlot(index=self._image_index, value=self._image_value, index_mapper=GridMapper(range= image_index_range), color_mapper=\ self._cmap(image_value_range), levels=self.num_levels) self.lineplot = ContourLinePlot(index=self._image_index, value=self._image_value, index_mapper=GridMapper(range= self.polyplot.index_mapper.range), levels=self.num_levels) # Add a left axis to the plot left = PlotAxis(orientation='left', title= "y", mapper=self.polyplot.index_mapper._ymapper, component=self.polyplot) self.polyplot.overlays.append(left) # Add a bottom axis to the plot bottom = PlotAxis(orientation='bottom', title= "x", mapper=self.polyplot.index_mapper._xmapper, component=self.polyplot) self.polyplot.overlays.append(bottom) # Add some tools to the plot self.polyplot.tools.append(PanTool(self.polyplot, constrain_key="shift")) self.polyplot.overlays.append(ZoomTool(component=self.polyplot, tool_mode="box", always_on=False)) self.polyplot.overlays.append(LineInspector(component=self.polyplot, axis='index_x', inspect_mode="indexed", write_metadata=True, is_listener=True, color="white")) self.polyplot.overlays.append(LineInspector(component=self.polyplot, axis='index_y', inspect_mode="indexed", write_metadata=True, color="white", is_listener=True)) # Add these two plots to one container contour_container = OverlayPlotContainer(padding=20, use_backbuffer=True, unified_draw=True) contour_container.add(self.polyplot) contour_container.add(self.lineplot) # Create a colorbar cbar_index_mapper = LinearMapper(range=image_value_range) self.colorbar = ColorBar(index_mapper=cbar_index_mapper, plot=self.polyplot, padding_top=self.polyplot.padding_top, padding_bottom=self.polyplot.padding_bottom, padding_right=40, resizable='v', width=30) self.pd = ArrayPlotData(line_index = array([]), line_value = array([]), scatter_index = array([]), scatter_value = array([]), scatter_color = array([])) self.cross_plot = Plot(self.pd, resizable="h") self.cross_plot.height = 100 self.cross_plot.padding = 20 self.cross_plot.plot(("line_index", "line_value"), line_style="dot") self.cross_plot.plot(("scatter_index","scatter_value","scatter_color"), type="cmap_scatter", name="dot", color_mapper=self._cmap(image_value_range), marker="circle", marker_size=8) self.cross_plot.index_range = self.polyplot.index_range.x_range self.pd.set_data("line_index2", array([])) self.pd.set_data("line_value2", array([])) self.pd.set_data("scatter_index2", array([])) self.pd.set_data("scatter_value2", array([])) self.pd.set_data("scatter_color2", array([])) self.cross_plot2 = Plot(self.pd, width = 140, orientation="v", resizable="v", padding=20, padding_bottom=160) self.cross_plot2.plot(("line_index2", "line_value2"), line_style="dot") self.cross_plot2.plot(("scatter_index2","scatter_value2","scatter_color2"), type="cmap_scatter", name="dot", color_mapper=self._cmap(image_value_range), marker="circle", marker_size=8) self.cross_plot2.index_range = self.polyplot.index_range.y_range # Create a container and add components self.container = HPlotContainer(padding=40, fill_padding=True, bgcolor = "white", use_backbuffer=False) inner_cont = VPlotContainer(padding=0, use_backbuffer=True) inner_cont.add(self.cross_plot) inner_cont.add(contour_container) self.container.add(self.colorbar) self.container.add(inner_cont) self.container.add(self.cross_plot2)
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0.0, 16, num=16) ## obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(16) ## obj.spectrum_data.set_data('amplitude', empty_amplitude) background = array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) * 20 obj.spectrum_data.set_data('background', background) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "background"), value_scale="linear",\ type='bar', bar_width=0.8, color='auto') obj.spectrum_plot.plot(("frequency", "amplitude"), value_scale="linear",\ name="Spectrum", type='bar', bar_width=0.8, color='auto')#[0] obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 75.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Word Plots # Setup the unseen spectrum plot dum_frequencies = linspace(0.0, float(SAMPLING_RATE) / 4, num=NUM_SAMPLES / 4) obj.dum_spectrum_data = ArrayPlotData(frequency=dum_frequencies) dum_empty_amplitude = zeros(NUM_SAMPLES / 4) obj.dum_spectrum_data.set_data('amplitude', dum_empty_amplitude) obj.dum_spectrum_plot = Plot(obj.dum_spectrum_data) spec_renderer = obj.dum_spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red")[0] values = [zeros(NUM_SAMPLES / 4) for i in xrange(SPECTROGRAM_LENGTH)] p = WaterfallRenderer(index = spec_renderer.index, values = values, index_mapper = LinearMapper(range = obj.dum_spectrum_plot.\ index_mapper.range), value_mapper = LinearMapper(range = DataRange1D(low=0,\ high=SPECTROGRAM_LENGTH)), y2_mapper = LinearMapper(low_pos=0, high_pos=8, range=DataRange1D(low=0, high=15)), ) spectrogram_plot = p obj.spectrogram_plot = p dummy = Plot() dummy.title = "Current Spectral Envelope" dummy.padding = 50 dummy.index_axis.mapper.range = p.index_mapper.range dummy.index_axis.title = "Frequency (hz)" dummy.add(p) values2 = [zeros(NUM_SAMPLES / 4) for i in xrange(SPECTROGRAM_LENGTH)] p2 = WaterfallRenderer(index = spec_renderer.index, values = values2, index_mapper = LinearMapper(range = obj.dum_spectrum_plot.\ index_mapper.range), value_mapper = LinearMapper(range = DataRange1D(low=0,\ high=SPECTROGRAM_LENGTH)), y2_mapper = LinearMapper(low_pos=0, high_pos=8, range=DataRange1D(low=0, high=15)), ) spectrogram_plot2 = p2 obj.spectrogram_plot2 = p2 dummy2 = Plot() dummy2.title = "Target Spectral Envelope" dummy2.padding = 50 dummy2.index_axis.mapper.range = p.index_mapper.range dummy2.index_axis.title = "Frequency (hz)" dummy2.add(p2) container = HPlotContainer() container.add(dummy) container.add(dummy2) c2 = VPlotContainer() c2.add(container) c2.add(obj.spectrum_plot) return c2
def _create_plot_component(): # Create the data and datasource objects numpoints = 500 index = arange(numpoints) returns = random.lognormal(0.01, 0.1, size=numpoints) price = 100.0 * cumprod(returns) volume = abs(random.normal(1000.0, 1500.0, size=numpoints) + 2000.0) time_ds = ArrayDataSource(index) vol_ds = ArrayDataSource(volume, sort_order="none") price_ds = ArrayDataSource(price, sort_order="none") xmapper = LinearMapper(range=DataRange1D(time_ds)) vol_mapper = LinearMapper(range=DataRange1D(vol_ds)) price_mapper = LinearMapper(range=DataRange1D(price_ds)) price_plot = FilledLinePlot(index=time_ds, value=price_ds, index_mapper=xmapper, value_mapper=price_mapper, edge_color="blue", face_color="paleturquoise", alpha=0.5, bgcolor="white", border_visible=True) add_default_grids(price_plot) price_plot.overlays.append(PlotAxis(price_plot, orientation='left')) price_plot.overlays.append(PlotAxis(price_plot, orientation='bottom')) price_plot.tools.append( PanTool(price_plot, constrain=True, constrain_direction="x")) price_plot.overlays.append( ZoomTool(price_plot, drag_button="right", always_on=True, tool_mode="range", axis="index")) vol_plot = BarPlot(index=time_ds, value=vol_ds, index_mapper=xmapper, value_mapper=vol_mapper, line_color="transparent", fill_color="black", bar_width=1.0, bar_width_type="screen", antialias=False, height=100, resizable="h", bgcolor="white", border_visible=True) add_default_grids(vol_plot) vol_plot.underlays.append(PlotAxis(vol_plot, orientation='left')) vol_plot.tools.append( PanTool(vol_plot, constrain=True, constrain_direction="x")) container = VPlotContainer(bgcolor="lightblue", spacing=20, padding=50, fill_padding=False) container.add(vol_plot) container.add(price_plot) container.overlays.append( PlotLabel( "Financial Plot", component=container, #font="Times New Roman 24")) font="Arial 24")) return container
def _create_plot_component(): # Create the data and datasource objects # In order for the date axis to work, the index data points need to # be in units of seconds since the epoch. This is because we are using # the CalendarScaleSystem, whose formatters interpret the numerical values # as seconds since the epoch. numpoints = 500 index = create_dates(numpoints) returns = random.lognormal(0.01, 0.1, size=numpoints) price = 100.0 * cumprod(returns) volume = abs(random.normal(1000.0, 1500.0, size=numpoints) + 2000.0) time_ds = ArrayDataSource(index) vol_ds = ArrayDataSource(volume, sort_order="none") price_ds = ArrayDataSource(price, sort_order="none") xmapper = LinearMapper(range=DataRange1D(time_ds)) vol_mapper = LinearMapper(range=DataRange1D(vol_ds)) price_mapper = LinearMapper(range=DataRange1D(price_ds)) price_plot = FilledLinePlot(index=time_ds, value=price_ds, index_mapper=xmapper, value_mapper=price_mapper, edge_color="blue", face_color="paleturquoise", bgcolor="white", border_visible=True) price_plot.overlays.append(PlotAxis(price_plot, orientation='left')), # Set the plot's bottom axis to use the Scales ticking system bottom_axis = PlotAxis( price_plot, orientation="bottom", # mapper=xmapper, tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem())) price_plot.overlays.append(bottom_axis) hgrid, vgrid = add_default_grids(price_plot) vgrid.tick_generator = bottom_axis.tick_generator price_plot.tools.append( PanTool(price_plot, constrain=True, constrain_direction="x")) price_plot.overlays.append( ZoomTool( price_plot, drag_button="right", always_on=True, tool_mode="range", axis="index", max_zoom_out_factor=10.0, )) vol_plot = BarPlot(index=time_ds, value=vol_ds, index_mapper=xmapper, value_mapper=vol_mapper, line_color="transparent", fill_color="black", bar_width=1.0, bar_width_type="screen", antialias=False, height=100, resizable="h", bgcolor="white", border_visible=True) hgrid, vgrid = add_default_grids(vol_plot) # Use the same tick generator as the x-axis on the price plot vgrid.tick_generator = bottom_axis.tick_generator vol_plot.underlays.append(PlotAxis(vol_plot, orientation='left')) vol_plot.tools.append( PanTool(vol_plot, constrain=True, constrain_direction="x")) container = VPlotContainer(bgcolor="lightblue", spacing=40, padding=50, fill_padding=False) container.add(vol_plot) container.add(price_plot) container.overlays.append( PlotLabel( "Financial Plot with Date Axis", component=container, #font="Times New Roman 24")) font="Arial 24")) return container
def _brain_default(self): plot = Plot(self.brain_data, padding=0) plot.width = self.brain_voxels.shape[1] plot.height = self.brain_voxels.shape[0] plot.aspect_ratio = 1. plot.index_axis.visible = False plot.value_axis.visible = False renderer = plot.img_plot("axial", colormap=gray)[0] plot.color_mapper.range = DataRange1D(low=0., high=1.0) plot.bgcolor = 'pink' # Brain tools plot.tools.append(PanTool(plot, drag_button="right")) plot.tools.append(ZoomTool(plot)) imgtool = ImageInspectorTool(renderer) renderer.tools.append(imgtool) overlay = ImageInspectorOverlay(component=renderer, image_inspector=imgtool, bgcolor="white", border_visible=True) renderer.overlays.append(overlay) # Brain track cursor self.cursor = CursorTool2D(renderer, drag_button='left', color='red', line_width=2.0) self.cursor.on_trait_change(self.update_stackedhist, 'current_index') self.cursor.current_position = (0., 0.) renderer.overlays.append(self.cursor) # Brain colorbar colormap = plot.color_mapper colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range), color_mapper=colormap, plot=plot, orientation='v', resizable='v', width=20, padding=(30, 0, 0, 0)) colorbar.padding_top = plot.padding_top colorbar.padding_bottom = plot.padding_bottom # Brain_map plot2 = Plot(self.brain_data, padding=0) plot2.width = self.brain_voxels.shape[1] plot2.height = self.brain_voxels.shape[0] plot2.aspect_ratio = 1. plot2.index_axis.visible = False plot2.value_axis.visible = False renderer2 = plot2.img_plot("map_axial", colormap=gray)[0] plot2.color_mapper.range = DataRange1D(low=0., high=1.0) plot2.bgcolor = 'pink' plot2.range2d = plot.range2d # Brain_map tools plot2.tools.append(PanTool(plot2, drag_button="right")) plot2.tools.append(ZoomTool(plot2)) imgtool2 = ImageInspectorTool(renderer2) renderer2.tools.append(imgtool2) overlay2 = ImageInspectorOverlay(component=renderer2, image_inspector=imgtool2, bgcolor="white", border_visible=True) renderer2.overlays.append(overlay2) # Brain_map track cursor self.cursor2 = CursorTool2D(renderer2, drag_button='left', color='red', line_width=2.0) #self.cursor2.on_trait_change(self.update_stackedhist, 'current_index') self.cursor2.on_trait_change(self.cursor2_changed, 'current_index') self.cursor2.current_position = (0., 0.) renderer2.overlays.append(self.cursor2) # Brain_map colorbar colormap2 = plot2.color_mapper colorbar2 = ColorBar(index_mapper=LinearMapper(range=colormap2.range), color_mapper=colormap2, plot=plot2, orientation='v', resizable='v', width=20, padding=(30, 0, 0, 0)) colorbar2.padding_top = plot2.padding_top colorbar2.padding_bottom = plot2.padding_bottom # Create a container to position the plot and the colorbar side-by-side container = HPlotContainer(use_backbuffer=True, padding=(0, 0, 10, 10)) container.add(plot) container.add(colorbar) container.bgcolor = "lightgray" container2 = HPlotContainer(use_backbuffer=True, padding=(0, 0, 10, 10)) container2.add(plot2) container2.add(colorbar2) container2.bgcolor = "lightgray" Vcontainer = VPlotContainer(use_backbuffer=True) Vcontainer.add(container2) Vcontainer.add(container) Vcontainer.bgcolor = "lightgray" return Vcontainer
def get_plot_component(self): # Create the array plot data that will feed our plots data = self.model.data plot_data = ArrayPlotData( index=data['dates'], close=data['close'], volume=data['volume'], ) self.plot_data = plot_data # Need to make the FilledLinePlot manually since Plot doesn't # support that plot type. times = ArrayDataSource(data['dates']) prices = ArrayDataSource(data['close']) close_plot = FilledLinePlot( index=times, value=prices, index_mapper=LinearMapper(range=DataRange1D(times)), value_mapper=LinearMapper(range=DataRange1D(prices)), edge_color='blue', face_color='paleturquoise', bgcolor='white', border_visible=True) close_plot.padding = [40, 15, 15, 20] self.close_plot = close_plot # The second plotter object which generates our candle plot plotter2 = Plot(data=plot_data) low_plot = plotter2.plot(('index', 'close'), )[0] low_plot.height = 100 low_plot.resizable = 'h' low_plot.bgcolor = 'white' low_plot.border_visible = True low_plot.padding = [40, 15, 15, 20] low_plot.color = 'darkred' low_plot.line_width = 1.5 self.low_plot = low_plot # The third plotter for the bar plot. plotter3 = Plot(data=plot_data) bar_plot = plotter3.plot(('index', 'volume'), type='bar')[0] bar_plot.height = 100 bar_plot.resizable = 'h' bar_plot.bgcolor = 'white' bar_plot.border_visible = True bar_plot.padding = [40, 15, 15, 20] bar_plot.line_color = 'transparent' bar_plot.fill_color = 'black' bar_plot.bar_width = 3.0 bar_plot.bar_width_type = 'screen' bar_plot.antialias = False bar_plot.index_mapper = low_plot.index_mapper self.bar_plot = bar_plot for plot in (close_plot, low_plot, bar_plot): ticker = ScalesTickGenerator(scale=CalendarScaleSystem()) bottom_axis = PlotAxis(plot, orientation='bottom', tick_generator=ticker) plot.overlays.append(bottom_axis) plot.overlays.append(PlotAxis(plot, orientation='left')) hgrid, vgrid = add_default_grids(plot) vgrid.tick_generator = bottom_axis.tick_generator def vol_label_formatter(val): return '%.1E' % val bar_plot.overlays[-1].tick_label_formatter = vol_label_formatter container = VPlotContainer( bgcolor=(240 / 255., 240 / 255., 240 / 255., 1.0), spacing=20, padding=20, fill_padding=True, stack_order='top_to_bottom', use_back_buffer=True, ) container.add(close_plot) container.add(low_plot) container.add(bar_plot) close_plot.controller = RangeSelection(close_plot) zoom_overlay = ZoomOverlay(source=close_plot, destination=low_plot, other=bar_plot) container.overlays.append(zoom_overlay) return container
def _create_plot_component(self): from numpy import abs, cumprod, random # Chaco imports from chaco.api import ArrayDataSource, BarPlot, DataRange1D, \ LinearMapper, VPlotContainer, PlotAxis, \ FilledLinePlot, add_default_grids, PlotLabel from chaco.tools.api import PanTool, ZoomTool from chaco.scales.api import CalendarScaleSystem, ScaleSystem from chaco.scales_tick_generator import ScalesTickGenerator # Create the data and datasource objects # In order for the date axis to work, the index data points need to # be in units of seconds since the epoch. This is because we are using # the CalendarScaleSystem, whose formatters interpret the numerical values # as seconds since the epoch. numpoints = self.data.size index = np.arange(self.data.size) self.xsource = ArrayDataSource(index) #vol_ds = ArrayDataSource(volume, sort_order="none") self.ysource = ArrayDataSource(self.data, sort_order="none") xmapper = LinearMapper(range=DataRange1D(self.xsource)) #vol_mapper = LinearMapper(range=DataRange1D(vol_ds)) meas_mapper = LinearMapper(range=DataRange1D(self.ysource)) price_plot = FilledLinePlot(index=self.xsource, value=self.ysource, index_mapper=xmapper, value_mapper=meas_mapper, edge_color=tuple(cbrewer[0]), face_color="paleturquoise", bgcolor="gray", border_visible=True) price_plot.overlays.append(PlotAxis(price_plot, orientation='left')), # Set the plot's bottom axis to use the Scales ticking system # bottom_axis = PlotAxis(price_plot, orientation="bottom", # mapper=xmapper, # tick_generator=ScalesTickGenerator(scale=ScaleSystem())) # price_plot.overlays.append(bottom_axis) # hgrid, vgrid = add_default_grids(price_plot) # vgrid.tick_generator = bottom_axis.tick_generator # # price_plot.tools.append(PanTool(price_plot, constrain=True, # constrain_direction="x")) # price_plot.overlays.append(ZoomTool(price_plot, drag_button="right", # always_on=True, # tool_mode="range", # axis="index", # max_zoom_out_factor=10.0, # )) container = VPlotContainer(bgcolor="lightblue", spacing=40, padding=50, fill_padding=False) container.add(price_plot) container.overlays.append(PlotLabel(self.title, component=container, # font="Times New Roman 24")) )) return container
def _create_plot_component(self, recalc=False): container = VPlotContainer() ### Assemble the scatter plot of the Efficient Frontier x, y = self.get_stock_data() if not hasattr(self, "efx") or recalc: efx, efy, allocations = self.get_ef_data() else: efx = self.efx efy = self.efy p = self.portfolio symbs = p.symbols pd = ArrayPlotData(x=x, y=y, efx=efx, efy=efy, mp_x=[self.model_portfolio_x], mp_y=[self.model_portfolio_y]) # Create some plots of the data plot = Plot(pd, title="Efficient Frontier") # Create a scatter plot (and keep a handle on it) stockplt = plot.plot(("x", "y"), color="transparent", type="scatter", marker="dot", marker_line_color="transparent", marker_color="transparent", marker_size=1)[0] efplt = plot.plot(("efx", "efy"), color=(0.0,0.5,0.0,0.25), type="scatter", marker="circle", marker_size=6)[0] efpltline = plot.plot(("efx", "efy"), color=(0.1,0.4,0.1,0.7), type="line")[0] # Create another one-point scatter for a model portfolio mp_plot = plot.plot(("mp_x", "mp_y"), color=(1.0, 0.5, 0.5, 0.25), type="scatter", market="triangle", market_size=7)[0] for i in range(len(p.stocks)): label = DataPointLabel(component=plot, data_point=(x[i], y[i]), label_position="bottom right", padding=4, bgcolor="transparent", border_visible=False, text=self.symbols[i], marker="circle", marker_color=(0.0,0.0,0.5,0.25), marker_line_color="lightgray", marker_size=6, arrow_size=8.0, arrow_min_length=7.0, font_size=14) plot.overlays.append(label) tool = DataLabelTool(label, drag_button="left", auto_arrow_root=True) label.tools.append(tool) stockplt.tools.append(ScatterInspector(stockplt, selection_mode="toggle", persistent_hover=False)) scatinsp = ScatterInspectorOverlay(stockplt, hover_color = "red", hover_marker_size = 8, hover_outline_color = (0.7, 0.7, 0.7, 0.5), hover_line_width = 1) stockplt.overlays.append(scatinsp) # Tweak some of the plot properties plot.padding = 50 stockplt.value_range.low=0.0 stockplt.value_range.high=0.1 stockplt.index_range.low=0.0 stockplt.index_range.high=0.1 # Attach some tools to the plot plot.tools.append(PanTool(plot, drag_button="right")) plot.overlays.append(ZoomTool(plot)) #### Assemble the "stacked area" plot if not hasattr(self, "efx") or recalc: a = self.get_ef_data()[2] else: a = self.allocations rts = a.keys() rts.sort() rts = np.array(rts) symbs = a[rts[0]].keys() symbs.sort() # "Transpose" symbols' weights to get vectors of weights for each symbol symb_data = np.array([[a[rt][symb] for rt in rts] for symb in symbs]) self.symbols2 = [Symbol(symbol=symbs[i], color=COLORS[i]) for i in range(len(symbs))] # Create a plot data object and give it this data bpd = ArrayPlotData() bpd.set_data("index", rts) bpd.set_data("allocations", symb_data) # Create a contour polygon plot of the data bplot = Plot(bpd, title="Allocations") bplot.stacked_bar_plot(("index", "allocations"), color = COLORS, outline_color = "gray") bplot.padding = 50 #bplot.legend.visible = True # Add a plot of the stocks stock_obj_list = [p.stocks[symb] for symb in symbs] #for itm in stock_obj_list: #itm.print_traits() #print "Has Cache?:", itm.stock_data_cache is not None splot = StockPlot(stocks=[p.stocks[symb] for symb in symbs], colors=COLORS).plot container.add(bplot) container.add(plot) container.add(splot) return container
def _time_plots_default(self): container = VPlotContainer(padding=50, spacing=50, bgcolor='transparent') container.add(self.zoomed_time_plot) container.add(self.overview_time_plot) return container
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0.0, float(SAMPLING_RATE) / 2, num=NUM_SAMPLES / 2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES / 2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) spec_renderer = obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red")[0] obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0.0, float(NUM_SAMPLES) / SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot values = [zeros(NUM_SAMPLES / 2) for i in xrange(SPECTROGRAM_LENGTH)] p = WaterfallRenderer( index=spec_renderer.index, values=values, index_mapper=LinearMapper(range=obj.spectrum_plot.index_mapper.range), value_mapper=LinearMapper( range=DataRange1D(low=0, high=SPECTROGRAM_LENGTH)), y2_mapper=LinearMapper(low_pos=0, high_pos=8, range=DataRange1D(low=0, high=15)), ) spectrogram_plot = p obj.spectrogram_plot = p dummy = Plot() dummy.padding = 50 dummy.index_axis.mapper.range = p.index_mapper.range dummy.index_axis.title = "Frequency (hz)" dummy.add(p) container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) c2 = VPlotContainer() c2.add(dummy) c2.add(container) return c2
def __init__(self, x, y, z): super(ImagePlot, self).__init__() self.pd_all = ArrayPlotData(imagedata=z) #self.pd_horiz = ArrayPlotData(x=x, horiz=z[4, :]) #self.pd_vert = ArrayPlotData(y=y, vert=z[:,5]) self._imag_index = GridDataSource(xdata=x, ydata=y, sort_order=("ascending", "ascending")) index_mapper = GridMapper(range=DataRange2D(self._imag_index)) self._imag_index.on_trait_change(self._metadata_changed, "metadata_changed") self._image_value = ImageData(data=z, value_depth=1) color_mapper = jet(DataRange1D(self._image_value)) self.color_plot = CMapImagePlot(index=self._imag_index, index_mapper=index_mapper, value=self._image_value, value_mapper=color_mapper, padding=20, use_backbuffer=True, unified_draw=True) #Add axes to image plot left = PlotAxis(orientation='left', title="Frequency (GHz)", mapper=self.color_plot.index_mapper._ymapper, component=self.color_plot) self.color_plot.overlays.append(left) bottom = PlotAxis(orientation='bottom', title="Time (us)", mapper=self.color_plot.index_mapper._xmapper, component=self.color_plot) self.color_plot.overlays.append(bottom) self.color_plot.tools.append( PanTool(self.color_plot, constrain_key="shift")) self.color_plot.overlays.append( ZoomTool(component=self.color_plot, tool_mode="box", always_on=False)) #Add line inspector tool for horizontal and vertical self.color_plot.overlays.append( LineInspector(component=self.color_plot, axis='index_x', inspect_mode="indexed", write_metadata=True, is_listener=True, color="white")) self.color_plot.overlays.append( LineInspector(component=self.color_plot, axis='index_y', inspect_mode="indexed", write_metadata=True, color="white", is_listener=True)) myrange = DataRange1D(low=amin(z), high=amax(z)) cmap = jet self.colormap = cmap(myrange) # Create a colorbar cbar_index_mapper = LinearMapper(range=myrange) self.colorbar = ColorBar(index_mapper=cbar_index_mapper, plot=self.color_plot, padding_top=self.color_plot.padding_top, padding_bottom=self.color_plot.padding_bottom, padding_right=40, resizable='v', width=30) #, ytitle="Magvec (mV)") #create horizontal line plot self.horiz_cross_plot = Plot(self.pd_horiz, resizable="h") self.horiz_cross_plot.height = 100 self.horiz_cross_plot.padding = 20 self.horiz_cross_plot.plot(("x", "horiz")) #, #line_style="dot") # self.cross_plot.plot(("scatter_index","scatter_value","scatter_color"), # type="cmap_scatter", # name="dot", # color_mapper=self._cmap(image_value_range), # marker="circle", # marker_size=8) self.horiz_cross_plot.index_range = self.color_plot.index_range.x_range #create vertical line plot self.vert_cross_plot = Plot(self.pd_vert, width=140, orientation="v", resizable="v", padding=20, padding_bottom=160) self.vert_cross_plot.plot(("y", "vert")) #, # line_style="dot") # self.vert_cross_plot.xtitle="Magvec (mV)" # self.vertica_cross_plot.plot(("vertical_scatter_index", # "vertical_scatter_value", # "vertical_scatter_color"), # type="cmap_scatter", # name="dot", # color_mapper=self._cmap(image_value_range), # marker="circle", # marker_size=8) self.vert_cross_plot.index_range = self.color_plot.index_range.y_range # Create a container and add components self.container = HPlotContainer(padding=40, fill_padding=True, bgcolor="white", use_backbuffer=False) inner_cont = VPlotContainer(padding=0, use_backbuffer=True) inner_cont.add(self.horiz_cross_plot) inner_cont.add(self.color_plot) self.container.add(self.colorbar) self.container.add(inner_cont) self.container.add(self.vert_cross_plot)
def create_plot(self): #-- Create the index for the x an y axes and the range over #-- which they vary self._image_index = GridDataSource(array([]), array([]), sort_order=("ascending","ascending")) image_index_range = DataRange2D(self._image_index) #-- I believe this is what allows tracking the mouse self._image_index.on_trait_change(self._metadata_changed, "metadata_changed") #-- Create the image values and determine their range self._image_value = ImageData(data=array([]), value_depth=1) image_value_range = DataRange1D(self._image_value) # Create the image plot self.imgplot = CMapImagePlot( index=self._image_index, value=self._image_value, index_mapper=GridMapper(range=image_index_range), color_mapper=self._cmap(image_value_range),) # Add a left axis to the plot left = PlotAxis(orientation='left', title= "axial", mapper=self.imgplot.index_mapper._ymapper, component=self.imgplot) self.imgplot.overlays.append(left) # Add a bottom axis to the plot bottom = PlotAxis(orientation='bottom', title= "radial", mapper=self.imgplot.index_mapper._xmapper, component=self.imgplot) self.imgplot.overlays.append(bottom) # Add some tools to the plot self.imgplot.tools.append(PanTool(self.imgplot,drag_button="right", constrain_key="shift")) self.imgplot.overlays.append(ZoomTool(component=self.imgplot, tool_mode="box", always_on=False)) # Create a colorbar cbar_index_mapper = LinearMapper(range=image_value_range) self.colorbar = ColorBar(index_mapper=cbar_index_mapper, plot=self.imgplot, padding_top=self.imgplot.padding_top, padding_bottom=self.imgplot.padding_bottom, padding_right=40, resizable='v', width=30) # Add a cursor self.cursor = CursorTool( self.imgplot, drag_button="left", color="white") # the cursor is a rendered component so it goes in the overlays list self.imgplot.overlays.append(self.cursor) # Create the two cross plots self.pd = ArrayPlotData(line_index = array([]), line_value = array([]), scatter_index = array([]), scatter_value = array([]), scatter_color = array([])) self.cross_plot = Plot(self.pd, resizable="h") self.cross_plot.height = 100 self.cross_plot.padding = 20 self.cross_plot.plot(("line_index", "line_value"), line_style="dot") self.cross_plot.plot(("scatter_index","scatter_value","scatter_color"), type="cmap_scatter", name="dot", color_mapper=self._cmap(image_value_range), marker="circle", marker_size=6) self.cross_plot.index_range = self.imgplot.index_range.x_range self.pd.set_data("line_index2", array([])) self.pd.set_data("line_value2", array([])) self.pd.set_data("scatter_index2", array([])) self.pd.set_data("scatter_value2", array([])) self.pd.set_data("scatter_color2", array([])) self.cross_plot2 = Plot(self.pd, width = 140, orientation="v", resizable="v", padding=20, padding_bottom=160) self.cross_plot2.plot(("line_index2", "line_value2"), line_style="dot") self.cross_plot2.plot(("scatter_index2","scatter_value2","scatter_color2"), type="cmap_scatter", name="dot", color_mapper=self._cmap(image_value_range), marker="circle", marker_size=8) self.cross_plot2.index_range = self.imgplot.index_range.y_range # Create a container and add sub-containers and components self.column_density = HPlotContainer(padding=40, fill_padding=True, bgcolor = "white", use_backbuffer=False) inner_cont = VPlotContainer(padding=0, use_backbuffer=True) inner_cont.add(self.cross_plot) self.imgplot.padding =20 inner_cont.add(self.imgplot) self.column_density.add(self.colorbar) self.column_density.add(inner_cont) self.column_density.add(self.cross_plot2)
class Bullseye(HasTraits): plots = Instance(GridPlotContainer) abplots = Instance(VPlotContainer) screen = Instance(Plot) horiz = Instance(Plot) vert = Instance(Plot) asum = Instance(Plot) bsum = Instance(Plot) process = Instance(Process) colormap = Enum("gray", "jet", "hot", "prism") invert = Bool(True) label = None gridm = None grid = None traits_view = View(HGroup(VGroup( HGroup( VGroup( Item("object.process.x", label="Centroid x", format_str=u"%.4g µm", tooltip="horizontal beam position relative to chip " "center"), Item("object.process.a", label="Major 4sig", format_str=u"%.4g µm", tooltip="major axis beam width 4 sigma ~ 1/e^2 width"), Item("object.process.t", label="Rotation", format_str=u"%.4g°", tooltip="angle between horizontal an major axis"), #Item("object.process.black", label="Black", # format_str=u"%.4g", # tooltip="background black level"), ), VGroup( Item("object.process.y", label="Centroid y", format_str=u"%.4g µm", tooltip="vertical beam position relative to chip " "center"), Item("object.process.b", label="Minor 4sig", format_str=u"%.4g µm", tooltip="major axis beam width 4 sigma ~ 1/e^2 width"), #Item("object.process.d", label="Mean width", # format_str=u"%.4g µm", # tooltip="mean beam width 4 sigma ~ 1/e^2 width"), #Item("object.process.e", label="Ellipticity", # format_str=u"%.4g", # tooltip="ellipticity minor-to-major width ratio"), #Item("object.process.peak", label="Peak", # format_str=u"%.4g", # tooltip="peak pixel level"), Item("object.process.include_radius", label="Include radius", format_str=u"%.4g µm", tooltip="energy inclusion radius according to ignore " "level, used to crop before taking moments"), ), style="readonly", ), VGroup( Item("object.process.capture.shutter", tooltip="exposure time per frame in seconds"), Item("object.process.capture.gain", tooltip="analog camera gain in dB"), Item("object.process.capture.framerate", tooltip="frames per second to attempt, may be limited by " "shutter time and processing speed"), Item("object.process.capture.average", tooltip="number of subsequent images to boxcar average"), Item("object.process.background", tooltip="background intensity percentile to subtract " "from image"), Item("object.process.ignore", tooltip="fraction of total intensity to ignore for " "cropping, determines include radius"), Item("object.process.crops", tooltip="fraction of total intensity to ignore for " "cropping, determines include radius"), ), HGroup( Item("object.process.active", tooltip="capture and processing running"), Item("object.process.capture.auto_shutter", tooltip="adjust the shutter time to " "yield acceptably exposed frames with peak values " "between .25 and .75"), Item("object.process.track", tooltip="adjust the region of interest to track the " "beam center, the size is not adjusted"), Item("object.process.capture.dark", tooltip="capture a dark image and subtract it from " "subsequent images, reset if gain or shutter change"), ), HGroup( UItem("colormap", tooltip="image colormap"), Item("invert", tooltip="invert the colormap"), ), UItem("abplots", editor=ComponentEditor(), width=-200, height=-300, resizable=False, tooltip="line sums (red), moments (blue) and " "2-sigma markers (green) along the major and minor axes", ), ), UItem("plots", editor=ComponentEditor(), width=800, tooltip="top right: beam image with 2-sigma and 6-sigma " "radius ellipses and axis markers (green). top left and bottom " "right: vertial and horizontal line sums (red), moments " "(blue) and 2-sigma markers (green). bottom left: beam data " "from moments"), layout="split", ), resizable=True, title=u"Bullseye ― Beam Profiler", width=1000) def __init__(self, **k): super(Bullseye, self).__init__(**k) self.data = ArrayPlotData() self.process.initialize() self.setup_plots() self.update_data() self.populate_plots() self.on_trait_change(self.update_data, "process.new_data", dispatch="fast_ui") def setup_plots(self): self.screen = Plot(self.data, resizable="hv", padding=0, bgcolor="lightgray", border_visible=False) self.screen.index_grid.visible = False self.screen.value_grid.visible = False px = self.process.capture.pixelsize w, h = self.process.capture.width, self.process.capture.height # value_range last, see set_range() self.screen.index_range.low_setting = -w/2*px self.screen.index_range.high_setting = w/2*px self.screen.value_range.low_setting = -h/2*px self.screen.value_range.high_setting = h/2*px self.horiz = Plot(self.data, resizable="h", padding=0, height=100, bgcolor="lightgray", border_visible=False) self.horiz.value_mapper.range.low_setting = \ -.1*self.process.capture.maxval self.horiz.index_range = self.screen.index_range self.vert = Plot(self.data, orientation="v", resizable="v", padding=0, width=100, bgcolor="lightgray", border_visible=False) for p in self.horiz, self.vert: p.index_axis.visible = False p.value_axis.visible = False p.index_grid.visible = True p.value_grid.visible = False self.vert.value_mapper.range.low_setting = \ -.1*self.process.capture.maxval self.vert.index_range = self.screen.value_range #self.vert.value_range = self.horiz.value_range self.mini = Plot(self.data, width=100, height=100, resizable="", padding=0, bgcolor="lightgray", border_visible=False) self.mini.index_axis.visible = False self.mini.value_axis.visible = False self.label = PlotLabel(component=self.mini, overlay_position="inside left", font="modern 10", text=self.process.text) self.mini.overlays.append(self.label) self.plots = GridPlotContainer(shape=(2, 2), padding=0, spacing=(5, 5), use_backbuffer=True, bgcolor="lightgray") self.plots.component_grid = [[self.vert, self.screen], [self.mini, self.horiz ]] self.screen.overlays.append(ZoomTool(self.screen, x_max_zoom_factor=1e2, y_max_zoom_factor=1e2, x_min_zoom_factor=0.5, y_min_zoom_factor=0.5, zoom_factor=1.2)) self.screen.tools.append(PanTool(self.screen)) self.plots.tools.append(SaveTool(self.plots, filename="bullseye.pdf")) self.asum = Plot(self.data, padding=0, height=100, bgcolor="lightgray", title="major axis", border_visible=False) self.bsum = Plot(self.data, padding=0, height=100, bgcolor="lightgray", title="minor axis", border_visible=False) for p in self.asum, self.bsum: p.value_axis.visible = False p.value_grid.visible = False p.title_font = "modern 10" p.title_position = "left" p.title_angle = 90 # lock scales #self.bsum.value_range = self.asum.value_range #self.bsum.index_range = self.asum.index_range self.abplots = VPlotContainer(padding=20, spacing=20, use_backbuffer=True,bgcolor="lightgray", fill_padding=True) self.abplots.add(self.bsum, self.asum) def populate_plots(self): self.screenplot = self.screen.img_plot("img", xbounds="xbounds", ybounds="ybounds", interpolation="nearest", colormap=color_map_name_dict[self.colormap], )[0] self.set_invert() self.grid = self.screenplot.index self.gridm = self.screenplot.index_mapper t = ImageInspectorTool(self.screenplot) self.screen.tools.append(t) self.screenplot.overlays.append(ImageInspectorOverlay( component=self.screenplot, image_inspector=t, border_size=0, bgcolor="transparent", align="ur", tooltip_mode=False, font="modern 10")) self.horiz.plot(("x", "imx"), type="line", color="red") self.vert.plot(("y", "imy"), type="line", color="red") self.horiz.plot(("x", "gx"), type="line", color="blue") self.vert.plot(("y", "gy"), type="line", color="blue") self.asum.plot(("a", "ima"), type="line", color="red") self.bsum.plot(("b", "imb"), type="line", color="red") self.asum.plot(("a", "ga"), type="line", color="blue") self.bsum.plot(("b", "gb"), type="line", color="blue") for p in [("ell1_x", "ell1_y"), ("ell3_x", "ell3_y"), ("a_x", "a_y"), ("b_x", "b_y")]: self.screen.plot(p, type="line", color="green", alpha=.5) for r, s in [("x", self.horiz), ("y", self.vert), ("a", self.asum), ("b", self.bsum)]: for p in "0 p m".split(): q = ("%s%s_mark" % (r, p), "%s_bar" % r) s.plot(q, type="line", color="green") def __del__(self): self.close() def close(self): self.process.active = False @on_trait_change("colormap") def set_colormap(self): p = self.screenplot m = color_map_name_dict[self.colormap] p.color_mapper = m(p.value_range) self.set_invert() p.request_redraw() @on_trait_change("invert") def set_invert(self): p = self.screenplot if self.invert: a, b = self.process.capture.maxval, 0 else: a, b = 0, self.process.capture.maxval p.color_mapper.range.low_setting = a p.color_mapper.range.high_setting = b # TODO: bad layout for one frame at activation, track # value_range seems to be updated after index_range, take this @on_trait_change("screen.value_range.updated") def set_range(self): if self.gridm is not None: #enforce data/screen aspect ratio 1 sl, sr, sb, st = self.gridm.screen_bounds dl, db = self.gridm.range.low dr, dt = self.gridm.range.high #dsdx = float(sr-sl)/(dr-dl) dsdy = float(st-sb)/(dt-db) #dt_new = db+(st-sb)/dsdx if dsdy: dr_new = dl+(sr-sl)/dsdy self.gridm.range.x_range.high_setting = dr_new l, r = self.screen.index_range.low, self.screen.index_range.high b, t = self.screen.value_range.low, self.screen.value_range.high px = self.process.capture.pixelsize self.process.capture.roi = [l, b, r-l, t-b] def update_data(self): if self.label is not None: self.label.text = self.process.text upd = self.process.data self.data.arrays.update(upd) self.data.data_changed = {"changed": upd.keys()} if self.grid is not None: self.grid.set_data(upd["xbounds"], upd["ybounds"])
def _create_plot_component(): # Create the data and datasource objects numpoints = 500 index = arange(numpoints) returns = random.lognormal(0.01, 0.1, size=numpoints) price = 100.0 * cumprod(returns) volume = abs(random.normal(1000.0, 1500.0, size=numpoints) + 2000.0) time_ds = ArrayDataSource(index) vol_ds = ArrayDataSource(volume, sort_order="none") price_ds = ArrayDataSource(price, sort_order="none") xmapper = LinearMapper(range=DataRange1D(time_ds)) vol_mapper = LinearMapper(range=DataRange1D(vol_ds)) price_mapper = LinearMapper(range=DataRange1D(price_ds)) price_plot = FilledLinePlot(index = time_ds, value = price_ds, index_mapper = xmapper, value_mapper = price_mapper, edge_color = "blue", face_color = "paleturquoise", alpha = 0.5, bgcolor = "white", border_visible = True) add_default_grids(price_plot) price_plot.overlays.append(PlotAxis(price_plot, orientation='left')) price_plot.overlays.append(PlotAxis(price_plot, orientation='bottom')) price_plot.tools.append(PanTool(price_plot, constrain=True, constrain_direction="x")) price_plot.overlays.append(ZoomTool(price_plot, drag_button="right", always_on=True, tool_mode="range", axis="index")) vol_plot = BarPlot(index = time_ds, value = vol_ds, index_mapper = xmapper, value_mapper = vol_mapper, line_color = "transparent", fill_color = "black", bar_width = 1.0, bar_width_type = "screen", antialias = False, height = 100, resizable = "h", bgcolor = "white", border_visible = True) add_default_grids(vol_plot) vol_plot.underlays.append(PlotAxis(vol_plot, orientation='left')) vol_plot.tools.append(PanTool(vol_plot, constrain=True, constrain_direction="x")) container = VPlotContainer(bgcolor = "lightblue", spacing = 20, padding = 50, fill_padding=False) container.add(vol_plot) container.add(price_plot) container.overlays.append(PlotLabel("Financial Plot", component=container, #font="Times New Roman 24")) font="Arial 24" )) return container
class OpenMMScriptRunner(HasTraits): plots = Instance(VPlotContainer) plots_created = Bool openmm_script_code = String status = String traits_view = View( Group( HGroup(spring, Item('status', style='readonly'), spring), Item('plots', editor=ComponentEditor(), show_label=False) ), width=800, height=600, resizable=True, title='OpenMM Script Runner' ) def __init__(self, **traits): super(OpenMMScriptRunner, self).__init__(**traits) self._plots_created = False q = Queue.Queue() # start up two threads. the first, t1, will run the script # and place the statedata into the queue # the second will remove elements from the queue and update the # plots in the UI t1 = threading.Thread(target=run_openmm_script, args=(self.openmm_script_code, q)) t2 = threading.Thread(target=self.queue_consumer, args=(q,)) t1.start() t2.start() def queue_consumer(self, q): """Main loop for a thread that consumes the messages from the queue and plots them""" self.status = 'Running...' while True: try: msg = q.get_nowait() if msg is None: break self.update_plot(msg) except Queue.Empty: time.sleep(0.1) self.status = 'Done' def create_plots(self, keys): """Create the plots Paramters --------- keys : list of strings A list of all of the keys in the msg dict. This should be something like ['Step', 'Temperature', 'Potential Energy']. We'll create the ArrayPlotData container in which each of these timeseries will get put. """ self.plots = VPlotContainer(resizable = "hv", bgcolor="lightgray", fill_padding=True, padding = 10) # this looks cryptic, but it is equivalent to # ArrayPlotData(a=[], b=[], c=[]) # if the keys are a,b,c. This just does it for all of the keys. self.plotdata = ArrayPlotData(**dict(zip(keys, [[]]*len(keys)))) # figure out which key will be the x axis if 'Step' in keys: x = 'Step' elif 'Time (ps)' in keys: x = 'Time (ps)' else: raise ValueError('The reporter published neither the step nor time' 'count, so I don\'t know what to plot on the x-axis!') colors = itertools.cycle(['blue', 'green', 'silver', 'pink', 'lightblue', 'red', 'darkgray', 'lightgreen',]) for y in filter(lambda y: y != x, keys): self.plots.add(chaco_scatter(self.plotdata, x_name=x, y_name=y, color=colors.next())) def update_plot(self, msg): """Add data points from the message to the plots Paramters --------- msg : dict This is the message sent over the Queue from the script """ if not self.plots_created: self.create_plots(msg.keys()) self.plots_created = True for k, v in msg.iteritems(): current = self.plotdata.get_data(k) self.plotdata.set_data(k, np.r_[current, v])