def _ts_data_changed(self): """ Dataset has changed: update the plot. ENH: add the possibility to pass a dict to ArrayPlotData. """ print "data changed: updating the plot..." arr_data = ArrayPlotData() for k, v in self.ts_data.items(): arr_data.set_data(k, v) self.ts_plot = ToolbarPlot(arr_data) for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]): self.ts_plot.plot(("index", k), name=k, color=colors[i % len(colors)]) if self.index_is_dates: # Index was an array of datetime: overwrite the x axis self.ts_plot.x_axis = None x_axis = PlotAxis(self.ts_plot, orientation="bottom", tick_generator=ScalesTickGenerator( scale=CalendarScaleSystem())) self.ts_plot.overlays.append(x_axis) self.ts_plot.x_grid.tick_generator = x_axis.tick_generator if self.data_file: self.ts_plot.title = "Time series visualization from %s" % self.data_file else: self.ts_plot.title = "Time series visualization" attach_tools(self.ts_plot)
def draw_plot(self, toolbar=True, **pltkws): ''' Draw bare plot, including main plotting area, toolbar, etc... either at initialization or global redo''' if toolbar: plot=ToolbarPlot(self.plotdata, **pltkws) else: plot=Plot(self.plotdata, **pltkws) plot.title = self.plot_title plot.padding = 50 plot.legend.visible=False plot.tools.append(PanTool(plot)) zoom=BetterSelectingZoom(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) #indexlabels=[str(round(i,1)) for i in self.dataframe.index] #### If I do plot.index_axis, it actually removes the default values. #index_axis=LabelAxis(plot, orientation='top', ## positions=range(int(float(indexlabels[0])), ## int(float(indexlabels[-1]))), #positions=range(0,1000,100), #labels=indexlabels,#, resizable='hv', #title=self.indexname) #plot.underlays.append(index_axis) #plot.value_axis= LabelAxis(plot, orientation='left', positions=range(self.t_axis_samples), #mainlabels=['t1', 't2', 't3', 't4','t5', 't6'], resizable='hv', #title=self.t_axis_title) self.plot=plot return
def update_main_plot(self): """ Build main plot """ self.ts_plot = ToolbarPlot(self.arr_plot_data) for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]): renderer = self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)])[0] if self.index_is_dates: # Index was an array of datetime: overwrite the x axis self.ts_plot.x_axis = None x_axis = PlotAxis(self.ts_plot, orientation="bottom", tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem())) self.ts_plot.overlays.append(x_axis) self.ts_plot.x_grid.tick_generator = x_axis.tick_generator if self.data_file: self.ts_plot.title = ("Time series visualization from %s" % (os.path.split(self.data_file)[1])) else: self.ts_plot.title = "Time series visualization" attach_tools(self.ts_plot) # Attach the range selection to the last renderer; any one will do self.ts_plot.tools.append(RangeSelection(renderer, left_button_selects = False, auto_handle_event = False)) # Attach the corresponding overlay self._range_selection_overlay = RangeSelectionOverlay(renderer, metadata_name="selections") self.ts_plot.overlays.append(self._range_selection_overlay) # Grab a reference to the Time axis datasource and add a listener to its # selections metadata self.times_ds = renderer.index self.times_ds.on_trait_change(self._selections_changed)
def __init__(self, index, series1, series2, **kw): super(ExamplePlotApp, self).__init__(**kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('series1', series1) plot_data.set_data('series2', series2) self.plot = ToolbarPlot(plot_data) self.plot.plot(('index', 'series1'), color='auto') self.plot.plot(('index', 'series2'), color='auto')
def __init__(self, depth, data_series, **kw): super(MyPlot, self).__init__(**kw) plot_data = ArrayPlotData(index=depth) plot_data.set_data('data_series', data_series) self.plot = ToolbarPlot(plot_data, orientation='v', origin='top left') line = self.plot.plot(('index', 'data_series'))[0] line_inspector = LineInspector(component=line, write_metadata=True) line.tools.append(line_inspector) line.overlays.append(line_inspector)
def create_plots(self): self.eplot = ToolbarPlot(self.data) self.nplot = ToolbarPlot(self.data) # Name required or will appear twice in legend! plot_line_points(self.eplot, ('x', 'er'), color='orange', name='e1') plot_line_points(self.eplot, ('x', 'ei'), color='green', name='ie2') plot_line_points(self.nplot, ('x', 'nr'), color='orange', name='n') plot_line_points(self.nplot, ('x', 'ni'), color='green', name='ik') self.add_tools_title(self.eplot, 'Dielectric Function vs. Wavelength') self.add_tools_title(self.nplot, 'Index of Refraction vs. Wavelength ')
class GSODDataPlotterView(HasTraits): """ Application of the zoom tool to the GSOD plotting tool. Load a HDF file containing one or more timeseries and plot the entire data inside. The zoom tool allows to explore a subset of it. The legend allows to (de)select some timeseries. """ data_file = File() ts_data = Dict() ts_plot = Instance(ToolbarPlot) traits_view = View( VGroup(Item('data_file', style = 'simple', label="HDF file to load"), Item('ts_plot', editor=ComponentEditor(size=(800, 600)), show_label=False),), title='Chaco Plot with file loader and legend highlighter', width=900, height=800, resizable=True) def __init__(self, pandas_list = [], array_dict = {}, *args, **kw): """ If a (list of) pandas or a dict of arrays is passed, load them up. """ ts_data = {} super(GSODDataPlotterView, self).__init__(*args, **kw) if not isinstance(pandas_list, list): pandas_list = [pandas_list] if pandas_list: ts_data.update(pandas2array_dict(pandas_list)) if array_dict: ts_data.update(ts_dict) self.ts_data = ts_data # Now trigger the plot redraw def _data_file_changed(self): """ Update the data from the HDF5 file. """ self.ts_data = pandas_hdf_to_data_dict(self.data_file) assert("index" in self.ts_data) def _ts_data_changed(self): """ Dataset has changed: update the plot. ENH: add the possibility to pass a dict to ArrayPlotData. """ arr_data = ArrayPlotData() for k,v in self.ts_data.items(): arr_data.set_data(k,v) self.ts_plot = ToolbarPlot(arr_data) for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]): self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)]) if self.data_file: self.ts_plot.title = "Time series visualization from %s" % self.data_file else: self.ts_plot.title = "Time series visualization" attach_tools(self.ts_plot)
class MyPlot(HasTraits): toolbar_class = Type(MyToolbar) plot = Instance(ToolbarPlot) plot_data = Instance(ArrayPlotData) view = View(Item("plot", editor = ComponentEditor(), show_label = False), resizable = True) def __init__(self): x = randn(100); y = randn(100) self.plot_data = ArrayPlotData(x=x, y=y) self.plot = ToolbarPlot(self.plot_data, toolbar_class=self.toolbar_class) self.plot.plot(("x", "y"), "scatter")
def __init__(self, index, series1, series2, **kw): super(ExamplePlotApp, self).__init__(**kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('series1', series1) plot_data.set_data('series2', series2) self.plot = ToolbarPlot(plot_data) line_plot = self.plot.plot(('index', 'series1'), color='auto')[0] # Add pan and zoom tools line_plot.tools.append(PanTool(line_plot)) line_plot.tools.append(ZoomTool(line_plot)) # Set the domain_limits line_plot.index_mapper.domain_limits = (3.3, 6.6)
def _ts_data_changed(self): """ Dataset has changed: update the plot. ENH: add the possibility to pass a dict to ArrayPlotData. """ arr_data = ArrayPlotData() for k,v in self.ts_data.items(): arr_data.set_data(k,v) self.ts_plot = ToolbarPlot(arr_data) for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]): self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)]) if self.data_file: self.ts_plot.title = "Time series visualization from %s" % self.data_file else: self.ts_plot.title = "Time series visualization" attach_tools(self.ts_plot)
class ExamplePlotApp(HasTraits): plot = Instance(Plot) traits_view = View( Item( 'plot', editor=ComponentEditor(), width=600, height=600, show_label=False), resizable=True) def __init__(self, index, series1, series2, **kw): super(ExamplePlotApp, self).__init__(**kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('series1', series1) plot_data.set_data('series2', series2) self.plot = ToolbarPlot(plot_data) line_plot = self.plot.plot(('index', 'series1'), color='auto')[0] # Add pan and zoom tools line_plot.tools.append(PanTool(line_plot)) line_plot.tools.append(ZoomTool(line_plot)) # Set the domain_limits line_plot.index_mapper.domain_limits = (3.3, 6.6)
def update_analysis_plot(self): """ Build analysis plot """ self.ts_analysis_plot = ToolbarPlot(self.arr_plot_data) if self.tool_chooser == CORRELATION: self.corr_renderer = self.ts_analysis_plot.plot((self.ts1_chooser, self.ts2_chooser), type = "scatter", color = "blue")[0] self.ts_analysis_plot.title = "%s plotted against %s" % (self.ts1_chooser, self.ts2_chooser) self.ts_analysis_plot.index_axis.title = self.ts1_chooser self.ts_analysis_plot.value_axis.title = self.ts2_chooser elif self.tool_chooser == MA and self.ma_window_size > 0: ts1_ma = pandas.rolling_mean(self.arr_plot_data.get_data(self.ts1_chooser), self.ma_window_size) self.arr_plot_data.set_data("ts1_ma", ts1_ma) self.ts_analysis_plot.plot(("index", self.ts1_chooser), type = "scatter", color = "blue") self.ts_analysis_plot.plot(("index", "ts1_ma"), type = "line", color = "blue")
class ExamplePlotApp(HasTraits): plot = Instance(Plot) traits_view = View(Item('plot', editor=ComponentEditor(), width = 600, height = 600, show_label=False), resizable=True) def __init__(self, index, series1, series2, **kw): super(ExamplePlotApp, self).__init__(**kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('series1', series1) plot_data.set_data('series2', series2) self.plot = ToolbarPlot(plot_data) self.plot.plot(('index', 'series1'), color='auto') self.plot.plot(('index', 'series2'), color='auto')
class ExamplePlotApp(HasTraits): plot = Instance(Plot) traits_view = View(Item('plot', editor=ComponentEditor(), width=600, height=600, show_label=False), resizable=True) def __init__(self, index, series1, series2, **kw): super(ExamplePlotApp, self).__init__(**kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('series1', series1) plot_data.set_data('series2', series2) self.plot = ToolbarPlot(plot_data) self.plot.plot(('index', 'series1'), color='auto') self.plot.plot(('index', 'series2'), color='auto')
def draw_plot(self): '''Use this method as a way to either default a plot or call a full remake for when a global datasource changes. Datasource as an input also lets me easily adapt plot behavior when using inheritance ''' plot = ToolbarPlot(self.plotdata) #CHANGE FOR OTHER PLOTS plot.title = self.plot_title plot.padding = 50 plot.legend.visible = False plot.tools.append(PanTool(plot)) zoom = BetterSelectingZoom(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) plot.index_axis = LabelAxis( plot, orientation='bottom', positions=range(self.x_axis_samples), labels=['X0', 'X1', 'X2', 'X3', 'X4', 'X5'], resizable='hv', title=self.x_axis_title) plot.value_axis = LabelAxis( plot, orientation='left', positions=range(self.t_axis_samples), labels=['t1', 't2', 't3', 't4', 't5', 't6'], resizable='hv', title=self.t_axis_title) self.plot = plot return
def draw_plot(self, toolbar=True, **pltkws): ''' Draw bare plot, including main plotting area, toolbar, etc... either at initialization or global redo''' if toolbar: plot = ToolbarPlot(self.plotdata, **pltkws) else: plot = Plot(self.plotdata, **pltkws) # plot.active_tool = RangeSelection(plot) # plot.overlays.append(RangeSelectionOverlay(component=plot)) plot.title = self.plot_title plot.padding = 50 plot.legend.visible = False plot.tools.append(PanTool(plot)) zoom = BetterSelectingZoom(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) #indexlabels=[str(round(i,1)) for i in self.dataframe.index] #### If I do plot.index_axis, it actually removes the default values. #index_axis=LabelAxis(plot, orientation='top', ## positions=range(int(float(indexlabels[0])), ## int(float(indexlabels[-1]))), #positions=range(0,1000,100), #labels=indexlabels,#, resizable='hv', #title=self.indexname) #plot.underlays.append(index_axis) #plot.value_axis= LabelAxis(plot, orientation='left', positions=range(self.t_axis_samples), #mainlabels=['t1', 't2', 't3', 't4','t5', 't6'], resizable='hv', #title=self.t_axis_title) self.plot = plot return
def _make_plot(self): x = [row.x for row in self.rows] y = [row.y for row in self.rows] z = [row.z for row in self.rows] plotdata = ArrayPlotData(x=x, y=y) """ idx = linspace(1,len(x),len(x)) vals = z bar_width = 1.0 line_width = 5.0 index = ArrayDataSource(idx) index_range = DataRange1D(index) index_mapper = LinearMapper(range=index_range) value = ArrayDataSource(vals) value_range = DataRange1D(value) value_mapper = LinearMapper(range=value_range) test_plot = BarPlot(index=index, value=value, value_mapper = value_mapper, index_mapper=index_mapper, bgcolor="white", line_color="black", fill_color="cornflowerblue", bar_width=bar_width, line_width=line_width) """ test_plot = ToolbarPlot(plotdata) test_plot.plot(("x", "y"), type="scatter") # changing type to line will make the # plot a line plot! not recommended! container = HPlotContainer(test_plot) self.aplot = container
def create_plots(self): self.sigplot = ToolbarPlot(self.data) # Don't change names, used by DoubleSView! plot_line_points(self.sigplot, ('x', 'Scattering'), color='green', name='Scattering') plot_line_points(self.sigplot, ('x', 'Absorbance'), color='blue', name='Absorbance') plot_line_points(self.sigplot, ('x', 'Extinction'), color='red', name='Extinction') self.add_tools_title(self.sigplot, self.plot_title)
def draw_plot(self): '''Use this method as a way to either default a plot or call a full remake for when a global datasource changes. Datasource as an input also lets me easily adapt plot behavior when using inheritance ''' plot=ToolbarPlot(self.plotdata) #CHANGE FOR OTHER PLOTS plot.title = self.plot_title plot.padding = 50 plot.legend.visible=False plot.tools.append(PanTool(plot)) zoom=BetterSelectingZoom(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) plot.index_axis=LabelAxis(plot, orientation='bottom', positions=range(self.x_axis_samples), labels=['X0', 'X1', 'X2', 'X3', 'X4', 'X5'], resizable='hv', title=self.x_axis_title) plot.value_axis= LabelAxis(plot, orientation='left', positions=range(self.t_axis_samples), labels=['t1', 't2', 't3', 't4','t5', 't6'], resizable='hv', title=self.t_axis_title) self.plot=plot return
def update_main_plot(self): """ Build main plot """ self.ts_plot = ToolbarPlot(self.arr_plot_data) for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]): self.ts_plot.plot(("index", k), name=k, color=colors[i % len(colors)]) if self.index_is_dates: # Index was an array of datetime: overwrite the x axis self.ts_plot.x_axis = None x_axis = PlotAxis(self.ts_plot, orientation="bottom", tick_generator=ScalesTickGenerator( scale=CalendarScaleSystem())) self.ts_plot.overlays.append(x_axis) self.ts_plot.x_grid.tick_generator = x_axis.tick_generator if self.data_file: self.ts_plot.title = "Time series visualization from %s" % self.data_file else: self.ts_plot.title = "Time series visualization" attach_tools(self.ts_plot)
def update_analysis_plot(self): """ Build analysis plot """ self.ts_analysis_plot = ToolbarPlot(self.arr_plot_data) if self.tool_chooser == CORRELATION: self.ts_analysis_plot.plot((self.ts1_chooser, self.ts2_chooser), type = "scatter", color = "blue") self.ts_analysis_plot.title = "%s plotted against %s" % (self.ts1_chooser, self.ts2_chooser) self.ts_analysis_plot.index_axis.title = self.ts1_chooser self.ts_analysis_plot.value_axis.title = self.ts2_chooser elif self.tool_chooser == MA and self.ma_window_size > 0: ts1_ma = pandas.rolling_mean(self.arr_plot_data.get_data(self.ts1_chooser), self.ma_window_size) self.arr_plot_data.set_data("ts1_ma", ts1_ma) self.ts_analysis_plot.plot(("index", self.ts1_chooser), type = "scatter", color = "blue") self.ts_analysis_plot.plot(("index", "ts1_ma"), type = "line", color = "blue")
def _ts_plot_default(self): """ Initialize the plot. """ # Store the data arr_data = ArrayPlotData(x=self.ts_data["index"], y1=self.ts_data["ts1"], y2=self.ts_data["ts2"]) # Plot container plot = ToolbarPlot(arr_data) # Plot curves plot.plot(("x", "y1"), name="ts 1", color="red") plot.plot(("x", "y2"), name="ts 2", color="blue") plot.title = "Multi timeseries plotter" return plot
def _plot_default(self, toolbar=True, **pltkwds): ''' Draw bare plot, including main plotting area, toolbar, etc... either at initialization or global redo''' if toolbar: self.plot = ToolbarPlot(self.plotdata, **pltkwds) else: self.plot = Plot(self.plotdata, **pltkwds) self.plot.title = self.title self.plot.padding = 50 self.plot.legend.visible = False self.plot.tools.append(PanTool(self.plot)) zoom = BetterSelectingZoom(component=self.plot, tool_mode="box", always_on=False) self.plot.overlays.append(zoom)
def update_main_plot(self): """ Build main plot """ self.ts_plot = ToolbarPlot(self.arr_plot_data) for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]): self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)]) if self.index_is_dates: # Index was an array of datetime: overwrite the x axis self.ts_plot.x_axis = None x_axis = PlotAxis(self.ts_plot, orientation="bottom", tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem())) self.ts_plot.overlays.append(x_axis) self.ts_plot.x_grid.tick_generator = x_axis.tick_generator if self.data_file: self.ts_plot.title = "Time series visualization from %s" % self.data_file else: self.ts_plot.title = "Time series visualization" attach_tools(self.ts_plot)
def _ts_plot_default(self): """ Initialize the plot. """ # Store the data arr_data = ArrayPlotData(x = self.ts_data["index"], y1 = self.ts_data["ts1"], y2 = self.ts_data["ts2"]) # Plot container plot = ToolbarPlot(arr_data) # Plot curves plot.plot(("x", "y1"), name = "ts 1", color = "red") plot.plot(("x", "y2"), name = "ts 2", color = "blue") plot.title = "Multi timeseries plotter" return plot
class MyPlot(HasTraits): """ Plot where depth is the index such that the plot is vertical and the origin is the upper left """ plot = Instance(ToolbarPlot) traits_view = View(Item('plot', editor=ComponentEditor(), width=600, height=600, show_label=False)) def __init__(self, depth, data_series, **kw): super(MyPlot, self).__init__(**kw) plot_data = ArrayPlotData(index=depth) plot_data.set_data('data_series', data_series) self.plot = ToolbarPlot(plot_data, orientation='v', origin='top left') line = self.plot.plot(('index', 'data_series'))[0] line_inspector = LineInspector(component=line, write_metadata=True) line.tools.append(line_inspector) line.overlays.append(line_inspector)
def _ts_data_changed(self): """ Dataset has changed: update the plot. ENH: add the possibility to pass a dict to ArrayPlotData. """ print "data changed: updating the plot..." arr_data = ArrayPlotData() for k,v in self.ts_data.items(): arr_data.set_data(k,v) self.ts_plot = ToolbarPlot(arr_data) for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]): self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)]) if self.index_is_dates: # Index was an array of datetime: overwrite the x axis self.ts_plot.x_axis = None x_axis = PlotAxis(self.ts_plot, orientation="bottom", tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem())) self.ts_plot.overlays.append(x_axis) self.ts_plot.x_grid.tick_generator = x_axis.tick_generator if self.data_file: self.ts_plot.title = "Time series visualization from %s" % self.data_file else: self.ts_plot.title = "Time series visualization" attach_tools(self.ts_plot)
class ExamplePlotApp(HasTraits): plot = Instance(Plot) traits_view = View(Item('plot', editor=ComponentEditor(), width = 600, height = 600, show_label=False), resizable=True) def __init__(self, index, series1, series2, **kw): super(ExamplePlotApp, self).__init__(**kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('series1', series1) plot_data.set_data('series2', series2) self.plot = ToolbarPlot(plot_data) line_plot = self.plot.plot(('index', 'series1'), color='auto')[0] # Add pan and zoom tools line_plot.tools.append(PanTool(line_plot)) line_plot.tools.append(ZoomTool(line_plot)) # Set the domain_limits line_plot.index_mapper.domain_limits = (3.3, 6.6)
def _plot1_default(self): return ToolbarPlot()
class GSODDataPlotterView(HasTraits): """ Application of the zoom tool to the GSOD plotting tool. Load a HDF file containing one or more timeseries and plot the entire data inside. The zoom tool allows to explore a subset of it. The legend allows to (de)select some timeseries. """ # UI controls data_file = File() # Tool controls tool_list = List([MA, CORRELATION]) tool_chooser = Enum(values="tool_list") ts_list = List() ts1_chooser = Enum(values="ts_list") ts2_chooser = Enum(values="ts_list") # Moving average window size (in number of observations) ma_window_size = Int(0) # Analysis details ts_analysis_details = Str("No details available") # Data ts_data = Dict() arr_plot_data = Instance(ArrayPlotData, ()) times_ds = Any() # arraydatasource for the time axis data index_is_dates = Bool() # Plots ts_plot = Instance(ToolbarPlot, ()) ts_analysis_plot = Instance(ToolbarPlot, ()) def trait_view(self, view): """ Build the view. The local namespace is """ return View( VGroup(Item('data_file', style='simple', label="HDF file to load"), HSplit(Item('ts_plot', editor=ComponentEditor(size=(400, 600)), show_label=False), VGroup(Item('tool_chooser', show_label = True, label="Choose tool"), Item('ts1_chooser', label="TS 1"), Item('ts2_chooser', label="TS 2", visible_when="tool_chooser in ['%s']" % CORRELATION), Item('ma_window_size', label="MA window size", visible_when="tool_chooser in ['%s']" % MA), Item('ts_analysis_plot', editor=ComponentEditor(size=(400, 600)), show_label=False), Item('ts_analysis_details', show_label = False, style = 'readonly', visible_when=("tool_chooser in ['%s']" % CORRELATION))),), ), title='Time-series plotter and analyzer', width=1300, height=800, resizable=True) def __init__(self, pandas_list = [], array_dict = {}, *args, **kw): """ If a (list of) pandas or a dict of arrays is passed, load them up. """ # Initialize the data content of the analysis tool ts_data = {} super(GSODDataPlotterView, self).__init__(*args, **kw) if not isinstance(pandas_list, list): pandas_list = [pandas_list] if pandas_list: array_dict_from_pandas, self.index_is_dates = pandas2array_dict(pandas_list) ts_data.update(array_dict_from_pandas) if array_dict: ts_data.update(array_dict) if ts_data: # Now trigger the plot redraw self.ts_data = ts_data def _data_file_changed(self): """ Update the data from the HDF5 file. """ ts_data, self.index_is_dates = pandas_hdf_to_data_dict(self.data_file) assert("index" in ts_data) self.ts_data = ts_data def _ts_data_changed(self): """ Dataset has changed: update the plots. ENH: add the possibility to pass a dict to ArrayPlotData constructor. """ for k,v in self.ts_data.items(): self.arr_plot_data.set_data(k,v) self.ts_list = self.ts_data.keys() self.update_main_plot() self.update_analysis_plot() def update_main_plot(self): """ Build main plot """ self.ts_plot = ToolbarPlot(self.arr_plot_data) for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]): renderer = self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)])[0] if self.index_is_dates: # Index was an array of datetime: overwrite the x axis self.ts_plot.x_axis = None x_axis = PlotAxis(self.ts_plot, orientation="bottom", tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem())) self.ts_plot.overlays.append(x_axis) self.ts_plot.x_grid.tick_generator = x_axis.tick_generator if self.data_file: self.ts_plot.title = ("Time series visualization from %s" % (os.path.split(self.data_file)[1])) else: self.ts_plot.title = "Time series visualization" attach_tools(self.ts_plot) # Attach the range selection to the last renderer; any one will do self.ts_plot.tools.append(RangeSelection(renderer, left_button_selects = False, auto_handle_event = False)) # Attach the corresponding overlay self._range_selection_overlay = RangeSelectionOverlay(renderer, metadata_name="selections") self.ts_plot.overlays.append(self._range_selection_overlay) # Grab a reference to the Time axis datasource and add a listener to its # selections metadata self.times_ds = renderer.index self.times_ds.on_trait_change(self._selections_changed) def _selections_changed(self, event): """ Selection of a time range on the first plot will triger a redraw of the correlation plot if present. """ if self.tool_chooser != CORRELATION: return if not isinstance(event, dict) or "selections" not in event: return corr_index = self.corr_renderer.index selections = event["selections"] if selections is None: corr_index.metadata.pop("selections", None) return else: low, high = selections data = self.times_ds.get_data() low_ndx = data.searchsorted(low) high_ndx = data.searchsorted(high) corr_index.metadata["selections"] = np.arange(low_ndx, high_ndx+1, 1, dtype=int) self.ts_analysis_plot.request_redraw() @on_trait_change("tool_chooser, ts1_chooser, ts2_chooser, ma_window_size") def update_analysis_plot(self): """ Build analysis plot """ self.ts_analysis_plot = ToolbarPlot(self.arr_plot_data) if self.tool_chooser == CORRELATION: self.corr_renderer = self.ts_analysis_plot.plot((self.ts1_chooser, self.ts2_chooser), type = "scatter", color = "blue")[0] self.ts_analysis_plot.title = "%s plotted against %s" % (self.ts1_chooser, self.ts2_chooser) self.ts_analysis_plot.index_axis.title = self.ts1_chooser self.ts_analysis_plot.value_axis.title = self.ts2_chooser elif self.tool_chooser == MA and self.ma_window_size > 0: ts1_ma = pandas.rolling_mean(self.arr_plot_data.get_data(self.ts1_chooser), self.ma_window_size) self.arr_plot_data.set_data("ts1_ma", ts1_ma) self.ts_analysis_plot.plot(("index", self.ts1_chooser), type = "scatter", color = "blue") self.ts_analysis_plot.plot(("index", "ts1_ma"), type = "line", color = "blue") @on_trait_change("tool_chooser, ts1_chooser, ts2_chooser") def update_analysis_details(self): if self.tool_chooser == CORRELATION: # Compute the correlation coefficients between the chosen TS ts1 = pandas.Series(self.ts_data[self.ts1_chooser]) ts2 = pandas.Series(self.ts_data[self.ts2_chooser]) corr_coefs = ts1.corr(ts2), ts1.corr(ts2, method = 'spearman'), ts1.corr(ts2, method = 'kendall') self.ts_analysis_details = ("Coefficients of correlation: Std = %5.3f, Spearman = %5.3f, Kendall = %5.3f." % corr_coefs) return
def __init__(self): x = randn(100); y = randn(100) self.plot_data = ArrayPlotData(x=x, y=y) self.plot = ToolbarPlot(self.plot_data, toolbar_class=self.toolbar_class) self.plot.plot(("x", "y"), "scatter")
def update(self): """Deviates from other plots in that these plots aren't meant to update in realtime via set-data, so it's easier to just wipe plotdata and redraws lines, basically as a static plot would work. Therefore, I don't separate update_data() and create_plots() and so forth. This method literally creates the plot from scratch. """ # At this point, assumes that arrays have been redraw so overwrite data or just self.plot = ToolbarPlot(self.data) #Requires access to arrayplotdata ostack = self.optical_stack #So don't have to recall property over and over # Depending on primary_axis, set X to lambdas Y to Angles or vice/ver # For x, resample wavelengths and choose current unit system via request() primary_x = self.optic_model.specparms.working_lambdas[::self. lam_samples. value] primary_y = self.optic_model.angles[::self.ang_samples.value] colormap = config.LINECMAP if self.primary_axis == 'Wavelengths': colormap = config.LINECMAP_LAMBDA primary_x, primary_y = primary_y, primary_x self.data.arrays = {} #Clear DATA!!! self.data.set_data('x', primary_x) linenames = [] #<-- To put into legend in sorted order # If angle averaging, can be many styles. If wavelength, just call mean if self.average: if self.primary_axis == 'Angles': # Why can't I just use panel.minor_xs().slice()? avg_array = self.optic_model.compute_average( self._model_attr).astype(complex) else: avg_array = ostack.minor_xs( self._model_attr).mean(axis=1).values.astype(complex) yout = self.infer_complex(avg_array) self.data.set_data('y', yout) plot_line_points(self.plot, ("x", "y"), name='%s Avg.' % (self._model_attr), style='both', line_width=4) #<--- Thick line # Plot angle dependence, bruteforce colromap else: # http://stackoverflow.com/questions/15140072/how-to-map-number-to-color-using-matplotlibs-colormap # http://stackoverflow.com/questions/27908032/custom-labels-in-chaco-legend/27950555#27950555 amin = primary_y[0] amax = primary_y[-1] if amin > amax: #If counting backwards angles like in transmission amax, amin = amin, amax norm = mpl.colors.Normalize(vmin=amin, vmax=amax) cmapper = cm.ScalarMappable( norm=norm, cmap=colormap).to_rgba #THIS IS A FUNCTION # yval is angle or wavelength for idx, yval in enumerate(primary_y): linecolor = cmapper(yval) linename = '%.2f' % yval linenames.append(linename) array = ostack[yval][self._model_attr].astype(complex) yout = self.infer_complex(array) self.data.set_data(linename, yout) plot_line_points( self.plot, ("x", linename), name=linename, color=linecolor, style='line' #<-- Don't plot marker ) # XXX --- At this point intercept self.data.arrays, and if 'x' is # only one with any data, then all lines are missing and could break out and set # to an image plot that says NO DATA or soemthing # https://media.readthedocs.org/pdf/chaco/latest/chaco.pdf if _plotdata_empty(self.data): self.plot = empty_image() return # Update plot title, legend, tools, labels # ---------------------------------------- #self.plot.title = '%s' % self.chosen_name self.plot.padding = 50 x_axis = PlotAxis( orientation='bottom', #top, bottom, left, righ title=self.x_unit, mapper=self.plot.x_mapper, component=self.plot) ylabel = '%s' % self.chosen_name if self.real_or_imag == 'imaginary': ylabel = ylabel + ' (imaginary)' y_axis = PlotAxis(orientation='left', title=ylabel, mapper=self.plot.y_mapper, component=self.plot) self.plot.underlays.append(y_axis) self.plot.underlays.append(x_axis) # Legend settings # http://code.enthought.com/projects/files/ETS3_API/enthought.chaco.legend.Legend.html # LEGEND EXAMPLES MISSING FOR CUSTOM OVERLAY # http://docs.enthought.com/chaco/user_manual/basic_elements/overlays.html if self.show_legend: self.plot.legend.labels = linenames self.plot.legend.visible = True self.plot.legend.bgcolor = (.8, .8, .8) #lightgray self.plot.legend.border_visible = True self.plot.legend.resizable = 'hv' #<--- doesn't work # Attach some tools to the plot #http://docs.enthought.com/chaco/api/tools.html self.plot.tools.append(PanTool(self.plot)) self.plot.tools.append(LineInspector(self.plot)) zoom = BetterSelectingZoom(component=self.plot, tool_mode="box", always_on=False) self.plot.overlays.append(zoom)