def _container_default(self): # Create the data and the PlotData object x = linspace(-14, 14, 100) y = sin(x) * x ** 3 plotdata = ArrayPlotData(x=x, y=y) # Create the scatter plot scatter = Plot(plotdata) scatter.plot(("x", "y"), type="scatter", color="blue") # Create the line plot line = Plot(plotdata) line.plot(("x", "y"), type="line", color="blue") # Add pan/zoom so we can see they are connected scatter.tools.append(PanTool(scatter)) scatter.tools.append(ZoomTool(scatter)) line.tools.append(PanTool(line)) line.tools.append(ZoomTool(line)) # Set the two plots' ranges to be the same scatter.index_range = line.index_range # Create a horizontal container and put the two plots inside it return HPlotContainer(scatter, line)
def _create_plot_component(): # Create some x-y data series (with NaNs) to plot x = linspace(-5.0, 15.0, 500) x[75:125] = nan x[200:250] = nan x[300:330] = nan pd = ArrayPlotData(index = x) pd.set_data("value1", jn(0, x)) pd.set_data("value2", jn(1, x)) # Create some line and scatter plots of the data plot = Plot(pd) plot.plot(("index", "value1"), name="j_0(x)", color="red", width=2.0) plot.plot(("index", "value2"), type="scatter", marker_size=1, name="j_1(x)", color="green") # Tweak some of the plot properties plot.title = "Plots with NaNs" plot.padding = 50 plot.legend.visible = True # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) return plot
def _create_plot_component(): # Create some data numpts = 5000 x = sort(random(numpts)) y = random(numpts) # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("index", x) pd.set_data("value", y) # Create the plot plot = Plot(pd) plot.plot(("index", "value"), type="scatter", marker="circle", index_sort="ascending", color="orange", marker_size=3, bgcolor="white") # Tweak some of the plot properties plot.title = "Scatter Plot" plot.line_width = 0.5 plot.padding = 50 # Attach some tools to the plot plot.tools.append(PanTool(plot, constrain_key="shift")) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) return plot
def createPlot(self, showDataTag ): # picks the desired channel out of the interleaved data stride = self.header.getChannels() # the first sample contains the data tag - the user has the # option to not display with the offset enabled offset = 0 if showDataTag else stride # we first grab the entire table and then select 1st ipp # along with the associated channel we're interested in. # I'm assuming this slice is a reference of the original. self.dataView = self.header.getBuffer()[ 0, offset::stride ] i = self.dataView['real'] q = self.dataView['imag'] xAxis = range( offset, i.size ) plotData = ArrayPlotData( xAxis=xAxis, i=i , q=q ) plot = Plot( plotData ) plot.plot( ("xAxis", "i"), type="line", color="blue") plot.plot( ("xAxis", "q"), type="line", color="red") plot.title = 'IQ Plot' return plot
class MyPlot(HasTraits): """ Displays a plot with a few buttons to control which overlay to display """ plot = Instance(Plot) status_overlay = Instance(StatusLayer) error_button = Button('Error') warn_button = Button('Warning') no_problem_button = Button('No problem') traits_view = View( HGroup(UItem('error_button'), UItem('warn_button'), UItem('no_problem_button')), UItem('plot', editor=ComponentEditor()), width=700, height=600, resizable=True, ) def __init__(self, index, data_series, **kw): super(MyPlot, self).__init__(**kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('data_series', data_series) self.plot = Plot(plot_data) self.plot.plot(('index', 'data_series')) def _error_button_fired(self, event): """ removes the old overlay and replaces it with an error overlay """ self.clear_status() self.status_overlay = ErrorLayer(component=self.plot, align='ul', scale_factor=0.25) self.plot.overlays.append(self.status_overlay) self.plot.request_redraw() def _warn_button_fired(self, event): """ removes the old overlay and replaces it with an warning overlay """ self.clear_status() self.status_overlay = WarningLayer(component=self.plot, align='ur', scale_factor=0.25) self.plot.overlays.append(self.status_overlay) self.plot.request_redraw() def _no_problem_button_fired(self, event): """ removes the old overlay """ self.clear_status() self.plot.request_redraw() def clear_status(self): if self.status_overlay in self.plot.overlays: # fade_out will remove the overlay when its done self.status_overlay.fade_out()
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 _fuel_cycle_plot_component(x, y, x_name, y_name): # Create some data # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("index", x) pd.set_data("value", y) # Create the plot plot = Plot(pd) plot.plot(("index", "value"), type="line", marker="circle", index_sort="ascending", color="red", marker_size=3, bgcolor="white") # Tweak some of the plot properties plot.title = "Fuel Cycle Plot" plot.line_width = 0.5 plot.padding = 100 plot.x_axis.title = x_name plot.x_axis.title_font = "Roman 16" plot.x_axis.tick_label_font = "Roman 12" plot.y_axis.title = y_name plot.y_axis.title_font = "Roman 16" plot.y_axis.tick_label_font = "Roman 12" # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) return plot
def update_show_curve(self): plotdata = ArrayPlotData(x=self.ct_hu, y=self.re_electronic_density) plot = Plot(plotdata) plot.plot(("x", "y"), type="line", color="blue") plot.title = self.name self.plot = plot
def _create_plot(self, max, min, dataobj, title): x = dataobj[:, 0] y = dataobj[:, 1] if y.max() > max: max = y.max() if y.min() < min: min = y.min() if self.sample_size > 1: y2 = dataobj[:, 6] y3 = dataobj[:, 7] if y3.max() > max: max = y3.max() if y2.min() < min: min = y2.min() plotdata = ArrayPlotData(x=x, y=y, y2=y2, y3=y3) else: plotdata = ArrayPlotData(x=x, y=y) plot = Plot(plotdata) plot.plot(("x", "y"), type="line", color="blue") if self.sample_size > 1: plot.plot(("x", "y2"), type="line", color="red") plot.plot(("x", "y3"), type="line", color="red") # plot.padding_right = 45 # plot.padding_left = 25 # plot.padding_top = 25 # plot.padding_bottom = 25 plot.title = title plot.title_font = "Arial 10" return plot, max, min
def _plot_default(self): data = ArrayPlotData(x=self.model.x, y=self.model.y) plot = Plot(data) plot.plot(('x', 'y'), style='line', color='green') plot.value_range.set_bounds(-self.model.a, self.model.a) plot.title = "a * exp(-b*x) * cos(omega*x + phase)" return plot
def _sig_phase_plot_default(self): plot = Plot(self.plot_data, padding=[75, 25, 25, 50], title='Signal Spectrum') plot.plot(('frequency', 'sig_phase'), index_scale='log', color='black') plot.index_axis.title = 'Frequency (Hz)' plot.value_axis.title = 'Power (dB)' return plot
def createWindow(widget): ''' Example on creating a new plot window in the main window MDI-Area ''' import plotWidget from PySide import QtGui from numpy import linspace from scipy.special import jn from chaco.api import ArrayPlotData, Plot window = widget.createNewWindow() container = plotWidget.plotContainer(window) plotWidget = plotWidget.PlotWidget(container) container.setPlotWidget(plotWidget) 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)) plot = Plot(pd, title=None, padding_left=60, padding_right=5, padding_top=5, padding_bottom=30, border_visible=True) plot.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red") plotWidget.setPlot(plot) layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom) layout.addWidget(container) window.setLayout(layout) window.show()
def _plot_default(self): # Create a GridContainer to hold all of our plots: 2 rows, 3 columns container = GridPlotContainer(shape=(2,3), spacing=(10,5), valign='top', bgcolor='lightgray') # Create x data x = linspace(-5, 15.0, 100) pd = ArrayPlotData(index = x) # Plot some Bessel functions and add the plots to our container for i in range(6): data_name = 'y{}'.format(i) pd.set_data(data_name, jn(i,x)) plot = Plot(pd) plot.plot(('index', data_name), color=COLOR_PALETTE[i], line_width=3.0) # Set each plot's aspect based on its position in the grid plot.set(height=((i % 3) + 1)*50, resizable='h') # Add to the grid container container.add(plot) return container
def __init__(self): # Create the data and the PlotData object price1 = random_walk(100) price2 = random_walk(100, start=50) times = np.arange(100) plotdata = ArrayPlotData(times=times, price1=price1, price2=price2) # Create the scatter plot plot1 = Plot(plotdata) plot1.plot(("times", "price1"), type="line", color="blue") plot1.plot(("times", "price1"), type="scatter", color="blue") plot2 = Plot(plotdata) plot2.plot(("times", "price2"), type="line", color="green") plot2.plot(("times", "price2"), type="scatter", color="green") scatterplot = Plot(plotdata) scatterplot.plot(("price2", "price1"), type="scatter", color="green") plot1.tools.append(PanTool(plot1)) plot1.tools.append(ZoomTool(plot1)) plot2.tools.append(PanTool(plot2)) plot2.tools.append(ZoomTool(plot2)) scatterplot.tools.append(PanTool(scatterplot)) scatterplot.tools.append(ZoomTool(scatterplot)) plot2.tools.append(ZoomTool(plot2)) lineplots = VPlotContainer(plot1, plot2) container = HPlotContainer(lineplots, scatterplot) self.plot = container self.plotdata = plotdata
class PlotExample(HasTraits): plot = Instance(Plot) traits_view = View(UItem('plot', editor=ComponentEditor()), width=400, height=400, resizable=True, ) def __init__(self, index, series_a, series_b, series_c, **kw): super(PlotExample, self).__init__(**kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('series_a', series_a) plot_data.set_data('series_b', series_b) plot_data.set_data('series_c', series_c) self.plot = Plot(plot_data) self.plot.plot(('index', 'series_a'), type='bar', bar_width=0.8, color='auto') self.plot.plot(('index', 'series_b'), type='bar', bar_width=0.8, color='auto') self.plot.plot(('index', 'series_c'), type='bar', bar_width=0.8, color='auto') # set the plot's value range to 0, otherwise it may pad too much self.plot.value_range.low = 0 # replace the index values with some nicer labels label_axis = LabelAxis(self.plot, orientation='bottom', title='Months', positions = list(range(1, 10)), labels = ['jan', 'feb', 'march', 'april', 'may'], small_haxis_style=True) self.plot.underlays.remove(self.plot.index_axis) self.plot.index_axis = label_axis self.plot.underlays.append(label_axis)
def create_chaco_plot(parent, data, args, type=''): #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)) #if not type: # type = ['plot'] #else: # type = [type, 'plot'] # Create some line plots of some of the data plot = Plot(data, title="Line Plot", padding=50, border_visible=True) plot.legend.visible = True #plot_fn = getattr(plot, '_'.join(type)) if type: renderers = plot.plot(args, plot=type) else: renderers = plot.plot(args) #plot.plot(("index", "y3"), name="j_3", color="blue") # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) plot.tools.append(TraitsTool(component=plot)) # This Window object bridges the Enable and Qt4 worlds, and handles events # and drawing. We can create whatever hierarchy of nested containers we # want, as long as the top-level item gets set as the .component attribute # of a Window. return Window(parent, -1, component = plot)
def __init__(self): # Create some data x = np.random.random(N_POINTS) y = np.random.random(N_POINTS) color = np.exp(-(x**2 + y**2)) # Create a plot data object and give it this data data = ArrayPlotData(index=x, value=y, color=color) # Create the plot plot = Plot(data) plot.plot(("index", "value", "color"), type="cmap_scatter", color_mapper=jet) # Create the colorbar, handing in the appropriate range and colormap colormap = plot.color_mapper colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range), color_mapper=colormap, orientation='v', resizable='v', width=30, padding=20) colorbar.padding_top = plot.padding_top colorbar.padding_bottom = plot.padding_bottom # Create a container to position the plot and the colorbar side-by-side container = HPlotContainer(plot, colorbar) self.plot = container
def __init__(self): super(ConnectedRange, self).__init__() x = linspace(-14, 14, 100) y = sin(x) * x ** 3 plotdata = ArrayPlotData(x=x, y=y) scatter = Plot(plotdata) scatter.plot(("x", "y"), type="scatter", color="blue") line = Plot(plotdata) #line = Plot(plotdata, orientation="v", default_origin="top left") line.plot(("x", "y"), type="line", color="red") self.container = HPlotContainer(scatter, line) scatter.tools.append(PanTool(scatter)) scatter.tools.append(ZoomTool(scatter)) line.tools.append(PanTool(line)) line.tools.append(ZoomTool(line)) #Axis link options, try them out #scatter.value_range = line.value_range # Link y-axis only #scatter.index_range = line.index_range # Link x-axis only scatter.range2d = line.range2d # Link both axes
def _sig_waveform_plot_default(self): plot = Plot(self.plot_data, padding=[75, 25, 25, 50], title='Signal Waveform') plot.plot(('time', 'sig_waveform'), color='black') plot.index_axis.title = 'Time (sec)' plot.value_axis.title = 'Signal (V)' return plot
class Viewer1D(Viewer): image = Array result = Array def _reconstruction_default(self): rows, cols = self.image.shape[:2] self.plot_data = ArrayPlotData(original=self.image[0], reconstruction=self.result[0]) aspect = cols/float(rows) old = Plot(self.plot_data) old.plot('original', ) old.title = 'Old' self.new = Plot(self.plot_data) self.new.plot('reconstruction') self.new.title = 'New' container = HPlotContainer(bgcolor='none') container.add(old) container.add(self.new) return container def update_plot(self): self.plot_data.set_data('reconstruction', self.result[0]) self.new.request_redraw()
def draw_histogram(self): """ Default function called when drawing the histogram. """ for component in self.container.components: self.container.remove(component) self.selection_handler.create_selection() if len(self.selection_handler.selected_indices) == 1: tuple_list = self.selection_handler.selected_indices[0] if self.AS_PANDAS_DATAFRAME: column_name = self.data.columns[tuple_list[1]] y = self.data[column_name] self.index = np.arange(self.nbins) hist = np.histogram(y, self.nbins)[0] plotdata = ArrayPlotData(x=self.index, y=hist) plot = Plot(plotdata) plot.plot(("x", "y"), type="bar", bar_width=0.5) self.container.add(plot) else: column = tuple_list[1] y = self.data[:, column] self.index = np.arange(self.nbins) hist = np.histogram(y, self.nbins)[0] plotdata = ArrayPlotData(x=self.index, y=hist) plot = Plot(plotdata) plot.plot(("x", "y"), type="bar", bar_width=0.5) self.container.add(plot) self.container.request_redraw() self.selection_handler.flush()
def _plot_default(self): plot = Plot(self.datasource) plot.plot( ('dates', 'values'), type='scatter') return 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) 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 _time_plot_default(self): time_plot = Plot(self.time_plot_data) time_plot.plot(('t', 'y')) time_plot.index_axis.title = "Time" time_plot.tools.append(PanTool(time_plot)) zoomtool = ZoomTool(time_plot, drag_button='right', always_on=True) time_plot.overlays.append(zoomtool) lines1 = CoordinateLineOverlay(component=time_plot, index_data=self.x1, value_data=self.y1, color=(0.75, 0.25, 0.25, 0.75), line_style='dash', line_width=1) time_plot.underlays.append(lines1) self.line_overlay1 = lines1 lines2 = CoordinateLineOverlay(component=time_plot, index_data=self.x2, value_data=self.y2, color=(0.2, 0.5, 1.0, 0.75), line_width=3) time_plot.underlays.append(lines2) self.line_overlay2 = lines2 return time_plot
def plot_spectrum(self,x,y,field): for i in range(len(self.x_koords)): x_gap=abs(x-self.x_koords[i]) y_gap=abs(y-self.y_koords[i]) if x_gap <self.toleranz and y_gap<self.toleranz: spectrum=self.spectra[i] wavelength=self.ivCamera.create_wavelength_for_plotting() xm = [self.plotrangemarker,self.plotrangemarker] #for red line in plot ym = [0,16000] #self.plotrangey plotdata = ArrayPlotData(x=wavelength, y=spectrum,xm=xm,ym=ym) plot = Plot(plotdata) plot.plot(("x", "y"), type="line", color="blue") plot.x_axis.title="Wavelength [nm]" plot.y_axis.title="Counts" #catch error if apd counts not loaded try: apd_counts = str(self.apd_counts[i]) except: apd_counts = str("0") plot.title = 'spectrum of QD ' +str(self.x_koords[i])+' '+str(self.y_koords[i])+' with APD at '+str(apd_counts) plot.overlays.append(ZoomTool(component=plot,tool_mode="box", always_on=False)) # damit man im Plot zoomen kann plot.tools.append(PanTool(plot, constrain_key="shift")) # damit man mit der Maus den Plot verschieben kann if field=='current': self.plot_current=plot if self.plotsetalways: self._plotrangeset_fired() if field=='compare': self.plot_compare=plot if self.plotsetalways: self._plotrangeset_fired()
def _dp_plot_default(self, parameter): plot = Plot(self.dp_data) for pt in ('scatter', 'line'): plot.plot(('f2_level', 'f1_spl'), type=pt, color='red') plot.plot(('f2_level', 'f2_spl'), type=pt, color='crimson') plot.plot(('f2_level', 'dpoae_spl'), type=pt, color='black') plot.plot(('f2_level', 'dp_spl'), type=pt, color='darkblue') plot.plot(('f2_level', 'dpoae_nf'), type=pt, color='gray') plot.plot(('f2_level', 'dp_nf'), type=pt, color='lightblue') plot.underlays = [] axis = PlotAxis(orientation='bottom', component=plot, title='f2 level (dB SPL)') plot.underlays.append(axis) axis = PlotAxis(orientation='left', component=plot, title='DPOAE level (dB SPL)') plot.underlays.append(axis) grid = PlotGrid(mapper=plot.index_mapper, component=plot, orientation='vertical', line_style='dot', line_color='lightgray') plot.underlays.append(grid) grid = PlotGrid(mapper=plot.value_mapper, component=plot, orientation='horizontal', line_style='dot', line_color='lightgray') plot.underlays.append(grid) return _DPPlot(plot=plot, parameter=parameter)
def _create_plot_component(): # Create some x-y data series to plot x = linspace(-2.0, 10.0, 40) pd = ArrayPlotData(index = x, y0=jn(0,x)) # Create some line plots of some of the data plot1 = Plot(pd, title="render_style = hold", padding=50, border_visible=True, overlay_border = True) plot1.legend.visible = True lineplot = plot1.plot(("index", "y0"), name="j_0", color="red", render_style="hold") # Attach some tools to the plot attach_tools(plot1) # Create a second scatter plot of one of the datasets, linking its # range to the first plot plot2 = Plot(pd, range2d=plot1.range2d, title="render_style = connectedhold", padding=50, border_visible=True, overlay_border=True) plot2.plot(('index', 'y0'), color="blue", render_style="connectedhold") attach_tools(plot2) # Create a container and add our plots container = HPlotContainer() container.add(plot1) container.add(plot2) return container
def _ch_plot_default(self): x = 0.26 y = 0. h_cross_x = np.array([self.x_low, self.x_high]) h_cross_y = np.array([y, y]) v_cross_x = np.array([x, x]) v_cross_y = np.array([self.y_low, self.y_high]) cross_hair_data = ArrayPlotData(h_cross_x=h_cross_x, h_cross_y=h_cross_y, v_cross_x=v_cross_x, v_cross_y=v_cross_y) ch_plot = Plot(cross_hair_data) ch_plot.plot(("h_cross_x", "h_cross_y"), type="line", color="green",) ch_plot.plot(("v_cross_x", "v_cross_y"), type="line", color="green",) while len(ch_plot.underlays) > 0: ch_plot.underlays.pop(0) ch_plot.range2d = self.img_plot.range2d cross_hair_tool = CrossHairs(ch_plot) ch_plot.tools.append(cross_hair_tool) self.crosshair = cross_hair_tool self.on_trait_change(self.draw_cross_hairs, "crosshair.selected_x, crosshair.selected_y") self.on_trait_change(self.render_julia, "crosshair.selected_x, crosshair.selected_y") return ch_plot
def _interp_data_button_fired(self): x = [row.x for row in self.rows] y = [row.y for row in self.rows] f = interp1d(asarray(x), asarray(y)) y2 = Array print x, sorted(x) y2 = [f(i) for i in sorted(x)] print y2 plotdata = ArrayPlotData(x=x, y=y) plotdata2 = ArrayPlotData(y=y2) test_plot = Plot(plotdata) test_plot.plot(("x", "y"), type="scatter") test_plot.plot(("x", "y"), type="line") test_plot_2 = Plot(plotdata2) # test_plot_2.plot("y2", type="line") # changing type to line w)ill make the # plot a line plot! not recommended! """ test_plot = plot(x,y,"b-", bgcolor="white") test_plot.hold() test_plot = plot(x,y2,"g-") """ container = HPlotContainer(test_plot) # ,test_plot_2) self.aplot = container
def __init__(self): # Create the data and the PlotData object x = linspace(-14, 14, 100) y = sin(x) * x ** 3 plotdata = ArrayPlotData(x=x, y=y) # Create the scatter plot scatter = Plot(plotdata) scatter.plot(("x", "y"), type="scatter", color="blue") # Create the line plot, rotated and vertically oriented line = Plot(plotdata, orientation="v", default_origin="top left") line.plot(("x", "y"), type="line", color="blue") # Create a horizontal container and put the two plots inside it self.container = HPlotContainer(scatter, line) # Add pan/zoom so we can see they are connected scatter.tools.append(PanTool(scatter)) scatter.tools.append(ZoomTool(scatter)) line.tools.append(PanTool(line)) line.tools.append(ZoomTool(line)) # Set the two plots' ranges to be the same scatter.range2d = line.range2d
def plotdata(self): self.y = [] self.x = [] self.fname.seek(0) for line in self.fname: self.y.append(int(line.split()[self.col + 1])) self.y = np.array(self.y) self.x = np.linspace(0, len(self.y) - 1, len(self.y)) print(self.x, self.y, type(self.x), type(self.y)) data = ArrayPlotData(x=self.x, y=self.y) plot = Plot(data) plot.plot(("x", "y"), type="line", color="blue") plot.title = "%s . %s" % (self.testItems, self.mem) self.plot = plot self.data = data
def intensity_histogram_plot_component(self): data = ArrayPlotData(x=self.bin_edges, y=self.hist) plot = Plot(data) plot.plot( ('x', "y"), type='bar', color='auto', bar_width=1, ) # without padding plot just doesn't seem to show up? plot.padding = 0 return plot
def _plot_default(self): plot = Plot(self.data) plot.plot(('t', 'y0'), color=colors[0]) plot.padding = 20 plot.padding_left = 40 plot.tools.append( PanTool(plot)) #, constrain=True, constrain_direction="y")) #TODO: zoomtool works on both axes, should only affect y plot.tools.append( ZoomTool(plot, tool_mode="range", constrain=True, constrain_direction="y")) return plot
def test_segment_plot_color_width(self): x = arange(10) y = arange(1, 11) c = arange(2, 7) w = arange(3, 8) data = ArrayPlotData(x=x, y=y, c=c, w=w) plot = Plot(data) plot.plot(('x', 'y', 'c', 'w'), "cmap_segment", color_mapper=viridis)[0] plot.do_layout((250, 250)) gc = PlotGraphicsContext((250, 250)) gc.render_component(plot) actual = gc.bmp_array[:, :, :] self.assertFalse(alltrue(actual == 255))
def __init__(self): super(ContainerExample, self).__init__() x = linspace(-14, 14, 100) y = sin(x) * x**3 plotdata = ArrayPlotData(x=x, y=y) scatter = Plot(plotdata) scatter.plot(("x", "y"), type="scatter", color="blue") line = Plot(plotdata) line.plot(("x", "y"), type="line", color="blue") container = VPlotContainer(scatter, line) self.plot = container
def _plot_default(self): # Create the plot plot = Plot(self.dataset) plot.plot(("index", "value"), type="scatter", marker='circle', color='blue') # Tweak some of the plot properties plot.title = "Scatter Plot" plot.line_width = 0.5 plot.padding = 50 return plot
def plotRU(self, rangeX=None, rangeY=None, save=False, filename=""): if save and filename == "": self.add_line("ERROR: I need a valid file name") return if save and filename.split('.')[-1] != "png": self.add_line("ERROR: File must end in .png") return if len(self.morseList) > 0: plotData = ArrayPlotData(x=self.Rlist, y=self.Ulist, morse=self.morseList, eigX=[self.Rlist[0], self.Rlist[-1]]) else: plotData = ArrayPlotData(x=self.Rlist, y=self.Ulist) for val in self.levelsToFind: if val < len(self.convergedValues): plotData.set_data( "eig" + str(val), [self.convergedValues[val], self.convergedValues[val]]) plot = Plot(plotData) if len(self.morseList) > 0: plot.plot(("x", "morse"), type="line", color="red") for val in self.levelsToFind: if val < len(self.convergedValues): plot.plot(("eigX", "eig" + str(val)), type="line", color="green") plot.plot(("x", "y"), type="line", color="blue") plot.plot(("x", "y"), type="scatter", marker_size=1.0, color="blue") # plot.index_axis.title = "Separation (r0)" if (self.scaled): plot.value_axis.title = "Potential (Eh * 2 * mu)" else: plot.value_axis.title = "Potential (Eh)" if len(self.plotRangeX) != 0: plot.x_axis.mapper.range.low = self.plotRangeX[0] plot.x_axis.mapper.range.high = self.plotRangeX[1] if len(self.plotRangeY) != 0: plot.y_axis.mapper.range.low = self.plotRangeY[0] plot.y_axis.mapper.range.high = self.plotRangeY[1] if not save: self.plot = plot else: plot.outer_bounds = [800, 600] plot.do_layout(force=True) gc = PlotGraphicsContext((800, 600), dpi=72) gc.render_component(plot) gc.save(filename)
def _plot_default(self): # Set up the spectrum plot spectrum_plot = Plot(self.spectrum_data) spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") spectrum_plot.padding = 50 spectrum_plot.title = "Spectrum" spec_range = list( spectrum_plot.plots.values())[0][0].value_mapper.range # noqa spec_range.low = 0.0 spec_range.high = 5.0 spectrum_plot.index_axis.title = 'Frequency (Hz)' spectrum_plot.value_axis.title = 'Amplitude' # Time series plot time_plot = Plot(self.time_data) time_plot.plot(("time", "amplitude"), name="Time", color="blue") time_plot.padding = 50 time_plot.title = "Time" time_plot.index_axis.title = 'Time (seconds)' time_plot.value_axis.title = 'Amplitude' time_range = list(time_plot.plots.values())[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_plot = Plot(self.spectrogram_plotdata) max_time = SPECTROGRAM_LENGTH * NUM_SAMPLES / SAMPLING_RATE max_freq = SAMPLING_RATE / 2 spectrogram_plot.img_plot( 'imagedata', name='Spectrogram', xbounds=(0, max_time), ybounds=(0, max_freq), colormap=hot, ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = 'Spectrogram' container = HPlotContainer() container.add(spectrum_plot) container.add(time_plot) container.add(spectrogram_plot) return container
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 draw_pc_plot(self): ''' Called to draw the PCA plot. ''' self.selection_handler.create_selection() if len(self.selection_handler.selected_indices) == 1: top_left = self.selection_handler.selected_indices[0][0:2] bot_right = self.selection_handler.selected_indices[0][2:4] data = self.table[top_left[0]:bot_right[0], top_left[1]:bot_right[1]] pc_red = self.pca.fit_transform(data) plotdata = ArrayPlotData(x=pc_red[:, 0], y=pc_red[:, 1]) plot = Plot(plotdata) plot.plot(("x", "y"), type='scatter') self.container.add(plot) self.container.request_redraw()
def _add_line_plots(self, plot): """Adds curve line plots to the ChacoPlot""" line_plots = [] for plot_config in self.line_plot_configs: line_plot = ChacoPlot(self._plot_data) # Customize text line_plot.trait_set(title=plot_config.title, padding=75, line_width=1) line_plot.x_axis.title = plot_config.x_label line_plot.y_axis.title = plot_config.y_label # Add pan and zoom tools line_plot.tools.append(PanTool(line_plot)) line_plot.overlays.append(ZoomTool(line_plot)) for name, kwargs in plot_config.line_config.items(): line = line_plot.plot((f"x_line_{name}", f"y_line_{name}"), type="line", **kwargs)[0] self._sub_axes[f'{name}_line_plot'] = line line_plots.append(line_plot) container = GridPlotContainer(*line_plots, shape=self._grid_shape, spacing=(0, 0), valign='top', bgcolor="none") self._component = HPlotContainer(plot, container, bgcolor="none") self._line_plots = line_plots
def _plot_default(self): self.plot_data = ArrayPlotData(x=self.continuous_data.x_data, y=self.continuous_data.y_data) plot = Plot(self.plot_data) plot.plot(("x", "y")) x_units = self.continuous_data.x_metadata["units"] y_units = self.continuous_data.y_metadata["units"] plot.index_axis.title = "Time ({})".format(x_units) plot.value_axis.title = "UV Absorption ({})".format(y_units) # Add zoom and pan tools to the plot zoom = BetterSelectingZoom(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) plot.tools.append(PanTool(component=plot)) return plot
def _create_plot_component(): # Create a random scattering of XY pairs x = random.uniform(0.0, 10.0, 50) y = random.uniform(0.0, 5.0, 50) pd = ArrayPlotData(x=x, y=y) plot = Plot(pd, border_visible=True, overlay_border=True) scatter = plot.plot(("x", "y"), type="scatter", color="lightblue")[0] # Tweak some of the plot properties plot.set(title="Scatter Inspector Demo", padding=50) # Attach some tools to the plot plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) # Attach the inspector and its overlay scatter.tools.append(ScatterInspector(scatter)) overlay = ScatterInspectorOverlay(scatter, hover_color="red", hover_marker_size=6, selection_marker_size=6, selection_color="yellow", selection_outline_color="purple", selection_line_width=3) scatter.overlays.append(overlay) return plot
def _create_plot_component(): # Create a fake dataset from which 2 dimensions will be displayed in a # scatter plot: x = np.random.uniform(0.0, 10.0, 50) y = np.random.uniform(0.0, 5.0, 50) data = pd.DataFrame({ "x": x, "y": y, "dataset": np.random.choice(list("abcdefg"), 50) }) plot_data = ArrayPlotData(x=x, y=y) plot = Plot(plot_data) scatter = plot.plot(("x", "y"), type="scatter")[0] # Attach the inspector and its overlays inspector = DataframeScatterInspector(component=scatter, data=data) scatter.tools.append(inspector) text_overlay = DataframeScatterOverlay(component=plot, inspector=inspector, bgcolor="black", alpha=0.6, text_color="white", border_color='none') plot.overlays.append(text_overlay) # Optional: add an overlay on the point to confirm what is hovered over # Note that this overlay magically knows about hovered points by # listening to renderer events rather than inspector events: point_overlay = ScatterInspectorOverlay(component=scatter, hover_color="red", hover_marker_size=6) scatter.overlays.append(point_overlay) return plot
def make_sin_plot(): """ Returns a chaco plot which plots a simple sin curve. """ idx = np.linspace(0, np.pi * 2, 100) val = np.sin(idx) plt = Plot(ArrayPlotData(x=idx, y=val), padding_top=30, padding_bottom=30, padding_left=35, padding_right=10, title='Sin Plot', fill_padding=False, background='transparent') plt.plot(('x', 'y'), color='red') return plt
def _create_plot_component(): pd = ArrayPlotData(x=random(100), y=random(100)) # Create some line plots of some of the data plot = Plot(pd) # Create a scatter plot and get a reference to it (separate from the # Plot object) because we'll need it for the regression tool below. scatterplot = plot.plot(("x", "y"), color="blue", type="scatter")[0] # Tweak some of the plot properties plot.padding = 50 # Attach some tools to the plot plot.tools.append(PanTool(plot, drag_button="right")) plot.overlays.append(ZoomTool(plot)) # Add the regression tool and overlay. These need to be added # directly to the scatterplot instance (and not the Plot instance). regression = RegressionLasso(scatterplot, selection_datasource=scatterplot.index) scatterplot.tools.append(regression) scatterplot.overlays.append( RegressionOverlay(scatterplot, lasso_selection=regression)) return plot
def _create_plot_component(): # Create a random scattering of XY pairs x = random.uniform(0.0, 10.0, 50) y = random.uniform(0.0, 5.0, 50) pd = ArrayPlotData(x = x, y = y) plot = Plot(pd, border_visible=True, overlay_border=True) scatter = plot.plot(("x", "y"), type="scatter", color="lightblue")[0] # Tweak some of the plot properties plot.set(title="Scatter Inspector Demo", padding=50) # Attach some tools to the plot plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) # Attach the inspector and its overlay inspector = ScatterInspector(scatter) scatter.tools.append(inspector) overlay = ScatterInspectorOverlay(scatter, hover_color="red", hover_marker_size=6, selection_marker_size=6, selection_color="yellow", selection_outline_color="purple", selection_line_width=3) scatter.overlays.append(overlay) # Optional: add a listener on inspector events: def echo(new): print("{} event on element {}".format(new.event_type, new.event_index)) inspector.on_trait_change(echo, "inspector_event") return plot
def make_plot(self, orientation): # make some data points x = arange(3) x = ArrayDataSource(x, sort_order="ascending") y = array([2, 0, 1]) # Plot the data pd = ArrayPlotData(x=x, y=y) plot = Plot(pd, orientation=orientation) line_plot = plot.plot(("x", "y"))[0] # Construct a fake screen space for the plots # otherwise would need to actually display the plots to get this index_mapper = LinearMapper(data_range=DataRange1D(low=0, high=2), high_pos=380, low_pos=20) value_mapper = LinearMapper(data_range=DataRange1D(low=0, high=2), high_pos=380, low_pos=20) plot.index_mapper = index_mapper plot.value_mapper = value_mapper line_plot.index_mapper = index_mapper line_plot.value_mapper = value_mapper return plot, line_plot
def _create_plot_component(): # Load state data states = pandas.read_csv('states.csv') lon = (states['longitude'] + 180.) / 360. lat = numpy.radians(states['latitude']) lat = (1 - (1. - numpy.log(numpy.tan(lat) + (1. / numpy.cos(lat))) / numpy.pi) / 2.0) populations = pandas.read_csv('state_populations.csv') data = populations['2010'] lon = lon.view(numpy.ndarray) lat = lat.view(numpy.ndarray) data = data.view(numpy.ndarray) plot = Plot(ArrayPlotData(index=lon, value=lat, color=data)) renderers = plot.plot( ("index", "value", "color"), type="cmap_scatter", name="unfunded", color_mapper=OrRd, marker="circle", outline_color='lightgray', line_width=1., marker_size=10, ) tile_cache = MBTileManager(filename='./map.mbtiles', min_level=2, max_level=4) # Need a better way add the overlays cmap = renderers[0] map = Map(cmap, tile_cache=tile_cache, zoom_level=3) cmap.underlays.append(map) plot.title = "2010 Population" plot.tools.append(PanTool(plot)) plot.tools.append(ZoomTool(plot)) plot.index_axis.title = "Longitude" plot.index_axis.tick_label_formatter = convert_lon plot.value_axis.title = "Latitude" plot.value_axis.tick_label_formatter = convert_lat cmap.overlays.append( ColormappedSelectionOverlay(cmap, fade_alpha=0.35, selection_type="mask")) colorbar = create_colorbar(plot.color_mapper) colorbar.plot = cmap colorbar.padding_top = plot.padding_top colorbar.padding_bottom = plot.padding_bottom container = HPlotContainer(use_backbuffer=True) container.add(plot) container.add(colorbar) container.bgcolor = "lightgray" return container
def _create_plot_component(): # Create some data npts = 2000 x = sort(random(npts)) y = random(npts) # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("index", x) pd.set_data("value", y) # Create the plot plot = Plot(pd) plot.plot(("index", "value"), type="scatter", name="my_plot", marker="circle", index_sort="ascending", color="red", marker_size=4, bgcolor="white") # Tweak some of the plot properties plot.title = "Scatter Plot With Lasso Selection" plot.line_width = 1 plot.padding = 50 # Right now, some of the tools are a little invasive, and we need the # actual ScatterPlot object to give to them my_plot = plot.plots["my_plot"][0] # Attach some tools to the plot lasso_selection = LassoSelection(component=my_plot, selection_datasource=my_plot.index, drag_button="left") #drag_button="right") my_plot.active_tool = lasso_selection my_plot.tools.append(ScatterInspector(my_plot)) lasso_overlay = LassoOverlay(lasso_selection=lasso_selection, component=my_plot) my_plot.overlays.append(lasso_overlay) # Uncomment this if you would like to see incremental updates: #lasso_selection.incremental_select = True return plot
def __init__(self): # Create the data and the PlotData object x = linspace(-14, 14, 100) y = sin(x) * x**3 plotdata = ArrayPlotData(x=x, y=y) # Create a scatter plot scatter_plot = Plot(plotdata) scatter_plot.plot(("x", "y"), type="scatter", color="blue") # Create a line plot line_plot = Plot(plotdata) line_plot.plot(("x", "y"), type="line", color="blue") # Create a horizontal container and put the two plots inside it container = HPlotContainer(line_plot, scatter_plot, spacing=100) self.plot = container
def _bar_default(self): index = np.arange(0, len(self.current_weight)) bar_data = ArrayPlotData(index=index, value=self.current_weight) self.bar_data = bar_data bar = Plot(data=bar_data) bar.plot(('index', 'value'), type='bar', bar_width=0.8, color='auto') label_axis = LabelAxis(bar, orientation='bottom', title='components', tick_interval=1, positions=index, labels=self.header, small_haxis_style=True) bar.underlays.remove(bar.index_axis) bar.index_axis = label_axis bar.range2d.y_range.high = 1.0 return bar
def _plot_default(self): # Create the data and the PlotData object x = linspace(-14, 14, 100) y = sin(x) * x**3 plotdata = ArrayPlotData(x=x, y=y) # Create a Plot and associate it with the PlotData plot = Plot(plotdata) # Create a scatter plot in the Plot plot.plot(("x", "y"), type="scatter", color="blue") plot.tools.append(PanTool(plot)) # Add our custom overlay to the plot overlay = CustomOverlay(plot) # Add the MoveTool to the overlay so it can be dragged around usin gthe # right mouse button. overlay.tools.append(MoveTool(overlay, drag_button="right")) plot.overlays.append(overlay) return plot
def _create_temperature_plot(self): plot_data = ArrayPlotData(time=np.array((0., 1.)), temperature=np.array((0., 40.)), fit=np.array((0., 0.))) plot = Plot(plot_data, width=50, height=40, padding=8, padding_left=64, padding_bottom=32) plot.plot(('time', 'temperature'), color='green') plot.index_axis.title = 'time [h]' plot.value_axis.title = 'temperature [C]' self.plot_data = plot_data self.temperature_plot = plot return self.temperature_plot
def _create_xy8_plot(self): plot_data_xy8_line = ArrayPlotData(counts2=np.array((0., 1.)), time=np.array((0., 0.)), fit=np.array((0., 0.))) plot = Plot(plot_data_xy8_line, width=50, height=40, padding=8, padding_left=64, padding_bottom=32) plot.plot(('time', 'counts2'), color='green', line_width=2) plot.index_axis.title = 'time [ns]' plot.value_axis.title = 'counts' #plot.title='counts' self.plot_data_xy8_line = plot_data_xy8_line self.xy8_plot = plot return self.xy8_plot
def create_plot(): numpoints = 100 low = -5 high = 15.0 x = linspace(low, high, numpoints) pd = ArrayPlotData(index=x) p = Plot(pd, bgcolor="lightgray", padding=50, border_visible=True) for t,i in sm.zip(cycle(['line','scatter']),sm.range(10)): pd.set_data("y" + str(i), jn(i,x)) p.plot(("index", "y" + str(i)), color=tuple(COLOR_PALETTE[i]), width = 2.0 * dpi_scale, type=t) p.x_grid.visible = True p.x_grid.line_width *= dpi_scale p.y_grid.visible = True p.y_grid.line_width *= dpi_scale p.legend.visible = True return p
def create_plot(): numpoints = 100 low = -5 high = 15.0 x = linspace(low, high, numpoints) pd = ArrayPlotData(index=x) p = Plot(pd, bgcolor="oldlace", padding=50, border_visible=True) for i in range(10): pd.set_data("y" + str(i), jn(i, x)) p.plot(("index", "y" + str(i)), color=tuple(COLOR_PALETTE[i]), width=2.0 * dpi_scale) p.x_grid.visible = True p.x_grid.line_width *= dpi_scale p.y_grid.visible = True p.y_grid.line_width *= dpi_scale p.legend.visible = True return p
def plot_clusters(self): ''' Plots the clusters after calling the .fit method of the sklearn kmeans estimator. ''' self.kmeans.n_clusters = self.n_clusters self.kmeans.fit(self.dataset) # Reducing dimensions of the dataset and the cluster centers for # plottting pca = PCA(n_components=2, whiten=True) cluster_centers = pca.fit_transform(self.kmeans.cluster_centers_) dataset_red = pca.fit_transform(self.dataset) removed_components = [] for component in self.container.components: removed_components.append(component) for component in removed_components: self.container.remove(component) for i in range(self.n_clusters): current_indices = find(self.kmeans.labels_ == i) current_data = dataset_red[current_indices, :] plotdata = ArrayPlotData(x=current_data[:, 0], y=current_data[:, 1]) plot = Plot(plotdata) plot.plot(("x", "y"), type='scatter', color=tuple(COLOR_PALETTE[i])) self.container.add(plot) plotdata_cent = ArrayPlotData(x=cluster_centers[:, 0], y=cluster_centers[:, 1]) plot_cent = Plot(plotdata_cent) plot_cent.plot(("x", "y"), type='scatter', marker='cross', marker_size=8) self.container.add(plot_cent) self.container.request_redraw()
class Viewer(HasTraits): container = None index = Array data = Array plot = Instance(Plot) plot_type = Enum("line", "scatter") #num_ticks = Int(0) num_ticks = 0 traits_view = View(Item("plot", editor=ComponentEditor(), show_label=False), width=300, height=300, resizable=False,) def __init__(self, max_points=200, advance_time=False, *args, **kwargs): super(Viewer, self).__init__(*args, **kwargs) self.advance_time = advance_time self.max_points = Int(max_points) self.plotdata = ArrayPlotData(index=self.index) self.plotdata.set_data('y', self.data) self.plot = Plot(self.plotdata) self.plot.plot(('index', 'y'), type='line', color='blue') def update(self, value): current_data = deque(self.data, self.max_points.default_value) num_ticks = self.num_ticks current_data.append(value) new_data = numpy.array(current_data) new_index = numpy.arange(num_ticks - len(new_data) + 1, num_ticks + 0.01) self.index = new_index self.data = new_data if self.advance_time: self.num_ticks += 1 def _data_changed(self): self.plotdata.set_data('y', self.data) self.plotdata.set_data('index', self.index)
class ER_plot_component(HasTraits): close = Event closing = False title = "" #view = View( Group(Item(name='container',editor=ComponentEditor(),show_label=False))) view = View( Group( Item(name='plot_ren', editor=ComponentEditor(size=(100, 100)), show_label=False)), handler=PlotHandler(), resizable=True, ) def __init__(self, p_obj, **traits): HasTraits.__init__(self, **traits) self.x = 0.2 self.p_obj = p_obj def make_plot(self): # ============================== #self.pd = ArrayPlotData(P_data=self.data.m_Pressures_array) # we store the array plotdata in the data object and update it there self.p_obj.values_array_pd = ArrayPlotData( P_data=self.p_obj.values_array) self.plot_ren = Plot(self.p_obj.values_array_pd) self.plot_ren.padding_left = 70 #80 self.plot_ren.padding_right = 5 self.plot_ren.padding_top = 5 self.plot_ren.padding_bottom = 40 self.plot_ren.x_axis.title = self.p_obj.x_axis self.plot_ren.y_axis.visible = False self.plot_ren.plot(("P_data"), type="line", color="blue", render_style='connectedhold') tick_gen = ScalesTickGenerator(scale=DefaultScale()) y_axis = PlotAxis(orientation='left', title=self.p_obj.y_axis, mapper=self.plot_ren.value_mapper, component=self.plot_ren, tick_generator=tick_gen) self.plot_ren.underlays.append(y_axis)