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 _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 __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_plot1 = Plot(plotdata) line_plot1.plot(("x", "y"), type="line", color="blue") line_plot2 = Plot(plotdata) line_plot2.plot(("x", "y"), type="line", color="red") # Create a vertical container containing two horizontal containers h_container1 = HPlotContainer() h_container2 = HPlotContainer() outer_container = VPlotContainer(h_container1, h_container2, stack_order="top_to_bottom") # Add the two plots to the first container h_container1.add(scatter_plot, line_plot1, line_plot2) # Now add the first line plot to the second container => it is removed # from the first, as each plot can only have one container h_container2.add(line_plot1) self.plot = outer_container
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
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 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 __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)
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 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 __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 line = Plot(plotdata) line.plot(("x", "y"), type="line", color="blue") # Create a vertical container and put the two plots inside it container = VPlotContainer(scatter, line) self.plot = container
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 _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): #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 _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 plotParsedData(self): self.plotdata = ArrayPlotData(x = self.data["ts"], wrdlt = self.data["wrdlt"]) self.plotA = Plot(self.plotdata) self.plotAA = self.plotA.plot(("x", "wrdlt"), type="line", color=(0,0.99,0), spacing=0, padding=0, alpha=0.7, use_downsampling=True, line_style = "dash") #render_style='connectedhold' # cache default axes limits self.Arng = [ self.plotA.x_axis.mapper.range.low, self.plotA.x_axis.mapper.range.high, self.plotA.y_axis.mapper.range.low, self.plotA.y_axis.mapper.range.high] self.plotA.x_axis.tick_label_position="inside" self.plotA.y_axis.tick_label_position="inside" self.container = VPlotContainer(self.plotA, spacing=0, padding=0, bgcolor="lightgray", use_backbuffer = True) self.plotA.spacing = 0 # set child padding after container set! self.plotA.padding = 0 self.plotA.tools.append(PanTool(self.plotA)) self.plotA.tools.append(ZoomTool(self.plotA)) self.plotA.overlays.append(BetterSelectingZoom(self.plotA)) legend = Legend(component=self.plotA, padding=1, align="ur") # to hide plots, make LegendHighlighter scale line to 0 on selection legend.tools.append(LegendHighlighter(legend, line_scale=0.0)) self.plots = {} self.plots["wrdlt"] = self.plotAA legend.plots = self.plots self.plotA.overlays.append(legend)
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 create_empty_plot(self): ''' place filler ''' vpc = VPlotContainer(bgcolor='lightgrey', height=1000, width=800) self.vplot_container = vpc return vpc
def __init__(self): self.data_context = DataContext() self.expression_context = ExpressionContext(self.data_context) self.plots = VPlotContainer() return
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, 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
class Trait(HasTraits): """ Main Drawing view for plot """ container = VPlotContainer(padding=0, fill_padding=True, bgcolor="lightgray", use_backbuffer=True) #container2 = OverlayPlotContainer(padding = 5, fill_padding = True, # bgcolor = "lightgray", use_backbuffer=True) str_time = Str float_open = Float float_high = Float float_low = Float float_close = Float float_volumn = Float plot = Instance(Plot) # TraitsUI view traits_view = View(Group( VGroup( #HGroup(Item("str_time", label="時間"), show_border = True, label = u"詳細資料"), HGroup(Item("str_time", label=_("time")), Item("float_open", label=_("open")), Item("float_high", label=_("high")), Item("float_low", label=_("low")), Item("float_close", label=_("close")), Item("float_volumn", label=_("volumn")), show_border=True, label=u"詳細資料"), VGroup(Item( "container", editor=ComponentEditor(), show_label=False)) )), resizable=True, width=size[0], height=size[1], handler=AnimationHandler(), title=u"Autotrader") #title=u"Plot 中文") # Constructor def __init__(self, dataframe=None): super(Trait, self).__init__() # main data frame for whole plot self.df = dataframe self.plot = self._create_plot() ############################################################################ ### adjust boundary def _compute_range2d(self): #if len(self.df)> 100: lowy = min(self.df.low[-100:]) lowy = lowy * 0.998 lowx = len(self.df) - 100 highy = max(self.df.high[-300:]) highy = highy * 1.002 highx = len(self.df) range2d = DataRange2D(low=(lowx, lowy), high=(highx, highy)) return range2d @on_trait_change('redraw', post_init=True) def _update_range2d(self): self.plot.range2d = self._compute_range2d() def _create_plot(self): # count data if len(self.df) > 0: self.indexes = np.arange(len(self.df.date_time)) time_ds = ArrayDataSource(self.indexes) vol_ds = ArrayDataSource(self.df.volumn.values, sort_order="none") xmapper = LinearMapper(range=DataRange1D(time_ds)) vol_mapper = LinearMapper(range=DataRange1D(vol_ds)) #################################################################### # create volumn plot vol_plot = BarPlot(index=time_ds, value=vol_ds, index_mapper=xmapper, value_mapper=vol_mapper, line_color="transparent", fill_color="blue", bar_width=0.6, antialias=False, height=100, resizable="h", origin="bottom left", bgcolor="white", border_visible=True ) vol_plot.padding = 30 vol_plot.padding_left = 40 vol_plot.tools.append( PanTool(vol_plot, constrain=True, constrain_direction="x")) add_default_grids(vol_plot) add_default_axes(vol_plot) #print vol_plot.index_mapper.range.high #print vol_plot.value_mapper.range.low, vol_plot.value_mapper.range.high self.vol_plot = vol_plot self.container.add(vol_plot) #################################################################### ## Create price plot sorted_vals = np.vstack( (self.df.open, self.df.high, self.df.low, self.df.close)) sorted_vals.sort(0) __bool = self.df.close.values - self.df.open.values self.up_boolean = __bool >= 0 self.down_boolean = np.invert(self.up_boolean) pd = ArrayPlotData( up_index=self.indexes[self.up_boolean], up_min=sorted_vals[0][self.up_boolean], up_bar_min=sorted_vals[1][self.up_boolean], up_bar_max=sorted_vals[2][self.up_boolean], up_max=sorted_vals[3][self.up_boolean], down_index=self.indexes[self.down_boolean], down_min=sorted_vals[0][self.down_boolean], down_bar_min=sorted_vals[1][self.down_boolean], down_bar_max=sorted_vals[2][self.down_boolean], down_max=sorted_vals[3][self.down_boolean], volumn=self.df.volumn.values, index=self.indexes ) price_plot = Plot(pd) up_plot = price_plot.candle_plot( ("up_index", "up_min", "up_bar_min", "up_bar_max", "up_max"), color=color_red, bgcolor="azure", bar_line_color="black", stem_color="black", end_cap=False)[0] down_plot = price_plot.candle_plot( ("down_index", "down_min", "down_bar_min", "down_bar_max", "down_max"), color=color_green, bar_line_color="black", stem_color="black", end_cap=False)[0] price_plot.fill_padding = True price_plot.padding = 30 price_plot.padding_left = 40 price_plot.tools.append(ZoomTool(component=price_plot, tool_mode="box", zoom_factor=1.2, always_on=False)) price_plot.tools.append(PanTool(price_plot, drag_button="left")) price_plot.tools.append( XYTool(price_plot, callback=self._update_ohlc)) # get data self._add_line_tool(up_plot) self._add_line_tool(down_plot) price_plot.range2d = self._compute_range2d() price_plot.index_mapper = vol_plot.index_mapper # maper vol_plot and price_plot self.price_plot = price_plot self.container.add(price_plot) def _update_ohlc(self, tool, xyarray): """Update Open, High, Low, Close, DateTime, items""" if xyarray.size == 2: # [x,y] ndarray xindex = int(round(xyarray[0])) if xindex >= 0 and xindex <= self.df.last_valid_index(): self.str_time = self.df.date_time[xindex].strftime("%H:%M") self.float_open = self.df.open[xindex] self.float_high = self.df.high[xindex] self.float_low = self.df.low[xindex] self.float_close = self.df.close[xindex] self.float_volumn = self.df.volumn[xindex] #print self.df.open[xindex] def _add_line_tool(self, input_plot): input_plot.overlays.append(LineInspector(input_plot, axis='index', #inspect_mode="indexed", # will show two line color="gray", write_metadata=True, is_listener=True)) ############################################################################ ### check plot data def update_plot_data(self): """Update drawing""" #t1 = time.time() # vol_plot value update self.vol_plot.value.set_data(self.df.volumn.values) # price_plot value update sorted_vals = np.vstack( (self.df.open, self.df.high, self.df.low, self.df.close)) sorted_vals.sort(0) __bool = self.df.close.values - self.df.open.values self.up_boolean = __bool >= 0 self.down_boolean = np.invert(self.up_boolean) self.price_plot.data.set_data( 'up_index', self.indexes[self.up_boolean]) self.price_plot.data.set_data( 'up_min', sorted_vals[0][self.up_boolean]) self.price_plot.data.set_data( 'up_bar_min', sorted_vals[1][self.up_boolean]) self.price_plot.data.set_data( 'up_bar_max', sorted_vals[2][self.up_boolean]) self.price_plot.data.set_data( 'up_max', sorted_vals[3][self.up_boolean]) self.price_plot.data.set_data( 'down_index', self.indexes[self.down_boolean]) self.price_plot.data.set_data( 'down_min', sorted_vals[0][self.down_boolean]) self.price_plot.data.set_data( 'down_bar_min', sorted_vals[1][self.down_boolean]) self.price_plot.data.set_data( 'down_bar_max', sorted_vals[2][self.down_boolean]) self.price_plot.data.set_data( 'down_max', sorted_vals[3][self.down_boolean]) #print "T1", time.time() - t1 def on_timer(self): # debug #self.df.volumn[self.df.last_valid_index()] = random.randrange(300,3000) #self.vol_plot.value.set_data(self.df.volumn.values) self.update_plot_data() self.container.request_redraw() return
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 __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_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