def get_polar_plot(): # Create theta N_POINTS = 5000 low, high = 0, np.pi theta = np.arange(low, high, (high - low) / N_POINTS) # Create the radius data radius = np.cos(3 * theta) # FIXME: at the moment PolarMapper does not actually do anything, so # we need to transform to Cartesian coordinates by hand xs = radius * np.cos(theta) ys = radius * np.sin(theta) x, y = get_data_sources(xs, ys) index_mapper = PolarMapper(range=DataRange1D(x)) value_mapper = PolarMapper(range=DataRange1D(y)) polar_plot = PolarLineRenderer(index=x, value=y, index_mapper=index_mapper, value_mapper=value_mapper, aspect_ratio=1.0, **PLOT_DEFAULTS) polar_plot.border_visible = False return polar_plot
def get_errorbar_plot(): x = np.linspace(1., 5., 10) y = 3.2 * x**2 + 4.0 y_with_noise = (y[None, :] + scipy.stats.norm(loc=0, scale=2.8).rvs( (10, 1))) means = y_with_noise.mean(0) stds = y_with_noise.std(0) x, y = get_data_sources(x=x, y=means) low = ArrayDataSource(means - stds) high = ArrayDataSource(means + stds) x_range = DataRange1D(low=0, high=6) y_range = DataRange1D(tight_bounds=False) y_range.add(y, low, high) errorbar_plot = ErrorBarPlot(index=x, value=y, index_mapper=LinearMapper(range=x_range), value_mapper=LinearMapper(range=y_range), value_low=low, value_high=high, endcap_size=11., **PLOT_DEFAULTS) add_axes(errorbar_plot, x_label='Test values', y_label='Measured') return errorbar_plot
def get_candle_plot(): means = np.array([0.2, 0.8, 0.5]) stds = np.array([1.0, 0.3, 0.5]) data = scipy.stats.norm(loc=means, scale=stds).rvs((100, 3)) x = ArrayDataSource(np.arange(3)) center = ArrayDataSource(data.mean(0)) bar_min = ArrayDataSource(data.mean(0) - data.std(0)) bar_max = ArrayDataSource(data.mean(0) + data.std(0)) stem_min = ArrayDataSource(data.min(0)) stem_max = ArrayDataSource(data.max(0)) x_range = DataRange1D(low=-1, high=3) y_range = DataRange1D(tight_bounds=False) y_range.add(center, bar_min, bar_max, stem_min, stem_max) candle_plot = CandlePlot(index=x, index_mapper=LinearMapper(range=x_range), value_mapper=LinearMapper(range=y_range), center_values=center, bar_min=bar_min, bar_max=bar_max, min_values=stem_min, max_values=stem_max, center_color='yellow', bar_color='orange', **PLOT_DEFAULTS) add_axes(candle_plot, x_label='Items', y_label='Values') return candle_plot
def __init__(self, xs, ys, index_bounds=None, value_bounds=None, *args, **kw): index = ArrayDataSource(xs) value = ArrayDataSource(ys) if index_bounds is not None: index_range = DataRange1D(low=index_bounds[0], high=index_bounds[1]) else: index_range = DataRange1D() index_range.add(index) index_mapper = LinearMapper(range=index_range) index_range.tight_bounds = False if value_bounds is not None: value_range = DataRange1D(low=value_bounds[0], high=value_bounds[1]) else: value_range = DataRange1D() value_range.add(value) value_mapper = LinearMapper(range=value_range) value_range.tight_bounds = False self.index = index self.value = value self.index_mapper = index_mapper self.value_mapper = value_mapper # self.color = "red" # self.line_width = 1.0 # self.line_style = "solid" super(BaseInset, self).__init__(*args, **kw) tick_label_font = 'Helvetica 8' left = PlotAxis(orientation='left', mapper=value_mapper, bgcolor=self.bgcolor, tick_label_font=tick_label_font) bottom = PlotAxis(orientation='bottom', mapper=index_mapper, bgcolor=self.bgcolor, tick_label_font=tick_label_font) self.underlays.append(left) self.underlays.append(bottom)
def get_contour_poly_plot(): NPOINTS_X, NPOINTS_Y = 600, 300 # Create a scalar field to contour xs = np.linspace(-2 * np.pi, +2 * np.pi, NPOINTS_X) ys = np.linspace(-1.5 * np.pi, +1.5 * np.pi, NPOINTS_Y) x, y = np.meshgrid(xs, ys) z = scipy.special.jn(2, x) * y * x # FIXME: we have set the xbounds and ybounds manually to work around # a bug in CountourLinePlot, see comment in contour_line_plot.py at # line 112 (the workaround is the +1 at the end) xs_bounds = np.linspace(xs[0], xs[-1], z.shape[1] + 1) ys_bounds = np.linspace(ys[0], ys[-1], z.shape[0] + 1) index = GridDataSource(xdata=xs_bounds, ydata=ys_bounds) index_mapper = GridMapper(range=DataRange2D(index)) value = ImageData(data=z, value_depth=1) color_mapper = dc.Blues(DataRange1D(value)) contour_plot = ContourPolyPlot(index=index, index_mapper=index_mapper, value=value, colors=color_mapper, **PLOT_DEFAULTS) add_axes(contour_plot, x_label='x', y_label='y') return contour_plot
def get_cmap_image_plot(): # Create a scalar field to colormap NPOINTS = 200 xs = np.linspace(-2 * np.pi, +2 * np.pi, NPOINTS) ys = np.linspace(-1.5*np.pi, +1.5*np.pi, NPOINTS) x, y = np.meshgrid(xs, ys) z = scipy.special.jn(2, x)*y*x index = GridDataSource(xdata=xs, ydata=ys) index_mapper = GridMapper(range=DataRange2D(index)) color_source = ImageData(data=z, value_depth=1) color_mapper = dc.Spectral(DataRange1D(color_source)) cmap_plot = CMapImagePlot( index=index, index_mapper=index_mapper, value=color_source, value_mapper=color_mapper, **PLOT_DEFAULTS ) add_axes(cmap_plot, x_label='x', y_label='y') return cmap_plot
def _render(self, gc): points = self.points func = self.canvas.map_screen if points: as_lines = True if as_lines: gc.begin_path() gc.move_to(*func(points[0][:2])) for p in points[1:]: gc.line_to(*func(p[:2])) if len(points) == 3: gc.line_to(*func(points[0][:2])) gc.close_path() gc.stroke_path() else: f = color_map_name_dict['hot'](DataRange1D(low_setting=0, high_setting=300)) for x, y, v in points: x, y = func((x, y)) gc.set_fill_color(f.map_screen(array([v]))[0]) gc.arc(x - 2, y - 2, 2, 0, 360) gc.fill_path() # if self.draw_text: gc.set_font_size(9) for x, y, v in points: x, y = func((x, y)) gc.set_text_position(x + 5, y + 5) gc.show_text('{:0.3f}'.format(v))
def from_palette_array(cls, palette, **traits): """ Creates a discrete color mapper from a palette array. """ palette = asarray(palette, dtype=float) # ignore range passed in and use fixed range instead traits.pop('range', None) range = DataRange1D(low=-0.5, high=len(palette) - 0.5) return cls(palette=palette, range=range, **traits)
def _set_group_colors(self, canvas=None): if canvas is None: canvas = self.canvas cs = {} if self.use_cmap: c = next( (k for k, v in color_map_dict.items() if v == self.cmap_name), None) if c: c = c(DataRange1D(low=0.0, high=1.0)) lns = sorted(list({p.identifier for p in self.positions})) nl = len(lns) scene = canvas.scene vs = c.map_screen(linspace(0, 1, nl)) cs = dict(zip(lns, [list(vi[:-1]) for vi in vs])) for i, p in enumerate(self.positions): color = cs.get(p.identifier, (1, 1, 0)) fcolor = ','.join([str(int(x * 255)) for x in color]) p.color = color # for pp in p.positions: pp = scene.get_item(p.position, klass=LoadIndicator) if pp is not None: pp.fill_color = fcolor
def get_contour_line_plot(): NPOINTS_X, NPOINTS_Y = 600, 300 # Create a scalar field to contour xs = np.linspace(-2 * np.pi, +2 * np.pi, NPOINTS_X) ys = np.linspace(-1.5 * np.pi, +1.5 * np.pi, NPOINTS_Y) x, y = np.meshgrid(xs, ys) z = scipy.special.jn(2, x) * y * x index = GridDataSource(xdata=xs, ydata=ys) index_mapper = GridMapper(range=DataRange2D(index)) value = ImageData(data=z, value_depth=1) color_mapper = dc.Blues(DataRange1D(value)) contour_plot = ContourLinePlot(index=index, index_mapper=index_mapper, value=value, colors=color_mapper, widths=list(range(1, 11)), **PLOT_DEFAULTS) add_axes(contour_plot, x_label='x', y_label='y') return contour_plot
def get_cmap_scatter_plot(): boston = datasets.load_boston() prices = boston['target'] lower_status = boston['data'][:, -1] nox = boston['data'][:, 4] x, y = get_data_sources(x=lower_status, y=prices) x_mapper, y_mapper = get_mappers(x, y) color_source = ArrayDataSource(nox) color_mapper = dc.reverse(dc.RdYlGn)(DataRange1D(low=nox.min(), high=nox.max())) scatter_plot = ColormappedScatterPlot( index=x, value=y, index_mapper=x_mapper, value_mapper=y_mapper, color_data=color_source, color_mapper=color_mapper, marker='circle', title='Color represents nitric oxides concentration', render_method='bruteforce', **PLOT_DEFAULTS) add_axes(scatter_plot, x_label='Percent lower status in the population', y_label='Median house prices') return scatter_plot
def get_multiline_plot(): prng = np.random.RandomState(seed=1234) x = np.linspace(0, 10, 50) y_data = np.column_stack([ x**2, 50 * np.sin(x), 50 * np.cos(x), 0.5 * x**2 + 2 * prng.randn(50), 0.7 * x**2 + prng.randn(50), ]) # data sources for the two axes xs = ArrayDataSource(np.arange(50)) ys = ArrayDataSource(np.arange(y_data.shape[1])) y_range = DataRange1D(low=-0.5, high=y_data.shape[1] - 0.5) y_mapper = LinearMapper(range=y_range) # data source for the multiple lines lines_source = MultiArrayDataSource(data=y_data.T) colors = ['blue', 'green', 'yellow', 'orange', 'red'] def color_generator(color_idx): return color_table[colors[color_idx]] multiline_plot = MultiLinePlot( index=xs, yindex=ys, index_mapper=LinearMapper(range=DataRange1D(xs)), value_mapper=y_mapper, value=lines_source, normalized_amplitude=1.0, use_global_bounds=False, color_func=color_generator, **PLOT_DEFAULTS) add_axes(multiline_plot, x_label='Days', y_label='Stock price changes') y_grid = PlotGrid(mapper=y_mapper, orientation="horizontal", line_style="dot", component=multiline_plot) multiline_plot.overlays.append(y_grid) return multiline_plot
def from_colormap(cls, colormap, steps, **traits): """ Creates a discrete color mapper from a palette array. """ from chaco.data_range_1d import DataRange1D traits.pop('range', None) range = DataRange1D(low=-0.5, high=steps - 0.5) # create the colormapper and sample from it colormapper = colormap(range, steps=steps) palette = colormapper.color_bands return cls(palette=palette, **traits)
def get_multiline_plot(): prices = datasets.fetch_mldata('regression-datasets stock') T, N_LINES = 70, 5 prices_data = prices['data'][:T, :N_LINES] prices_data -= prices_data[0, :] # data sources for the two axes xs = ArrayDataSource(np.arange(T)) ys = ArrayDataSource(np.arange(N_LINES)) y_range = DataRange1D(low=-0.5, high=N_LINES - 0.5) y_mapper = LinearMapper(range=y_range) # data source for the multiple lines lines_source = MultiArrayDataSource(data=prices_data.T) colors = ['blue', 'green', 'yellow', 'orange', 'red'] def color_generator(color_idx): return color_table[colors[color_idx]] multiline_plot = MultiLinePlot( index=xs, yindex=ys, index_mapper=LinearMapper(range=DataRange1D(xs)), value_mapper=y_mapper, value=lines_source, normalized_amplitude=1.0, use_global_bounds=False, color_func=color_generator, **PLOT_DEFAULTS) add_axes(multiline_plot, x_label='Days', y_label='Stock price changes') y_grid = PlotGrid(mapper=y_mapper, orientation="horizontal", line_style="dot", component=multiline_plot) multiline_plot.overlays.append(y_grid) return multiline_plot
def _create_colormap(self): if self.colormap_low is None: self.colormap_low = self.posterior.min() if self.colormap_high is None: self.colormap_high = self.posterior.max() colormap = Reds( DataRange1D(low=self.colormap_low, high=self.colormap_high)) return colormap
def _create_polar_plot(self, plotitem, data, color='black', width=1.0, dash="solid", grid="dot", value_mapper_class=PolarMapper, frac_noplot=0.3, **kwargs): if (type(data) != ndarray) and (len(data) == 2): data = transpose(array(data)) r_data, t_data = transpose(data) index_data = r_data * cos(t_data) value_data = r_data * sin(t_data) index = ArrayDataSource(index_data, sort_order='ascending') # Typically the value data is unsorted value = ArrayDataSource(value_data) index_range = DataRange1D() index_range.add(index) index_mapper = PolarMapper(range=index_range) value_range = DataRange1D() value_range.add(value) value_mapper = value_mapper_class(range=value_range) plot = MFnPolarLineRenderer(index=index, value=value, index_mapper=index_mapper, value_mapper=value_mapper, color=color, line_width=width, line_style=dash, grid_style=grid, frac_noplot=frac_noplot, origin_axis_visible=True) return plot
def init(self, parent): self.control = Bar() self.control.low = low = self.factory.low self.control.high = high = self.factory.high self.control.color_scalar = self.factory.color_scalar self.control.bar_width = self.factory.width self.control.scale = self.factory.scale # if self.factory.scale == 'power': # high = N = 1 / float(self.color_scalar) # A = 1 / self.high ** N self.control.cmap = color_map_name_dict[self.factory.colormap]( DataRange1D(low_setting=0, high_setting=1))
def _create_colormap(self): if self.colormap_low is None: self.colormap_low = self.matrix.min() if self.colormap_high is None: self.colormap_high = self.matrix.max() if self.colormap_low >= 0.0: colormap_factory = Reds else: colormap_factory = reverse(RdBu) colormap = colormap_factory( DataRange1D(low=self.colormap_low, high=self.colormap_high)) return colormap
def make_colorbar(self, plot, width=30, padding=20, orientation='v', resizable='v'): cm = gray(DataRange1D()) lm = LinearMapper() colorbar = ColorBar(orientation=orientation, resizable=resizable, width=width, padding=padding, index_mapper=lm, color_mapper=cm) if plot is not None: colorbar.trait_set( index_mapper=LinearMapper(range=plot.color_mapper.range), color_mapper=plot.color_mapper, plot=plot) return colorbar
def get_4d_scatter_plot(): boston = datasets.load_boston() prices = boston['target'] lower_status = boston['data'][:, -1] tax = boston['data'][:, 9] nox = boston['data'][:, 4] x, y = get_data_sources(x=lower_status, y=prices) x_mapper, y_mapper = get_mappers(x, y) color_source = ArrayDataSource(nox) color_mapper = dc.reverse(dc.RdYlGn)(DataRange1D(low=nox.min(), high=nox.max())) # normalize between 0 and 10 marker_size = tax / tax.max() * 10. scatter_plot = ColormappedScatterPlot( index=x, value=y, index_mapper=x_mapper, value_mapper=y_mapper, color_data=color_source, color_mapper=color_mapper, fill_alpha=0.8, marker='circle', marker_size=marker_size, title='Size represents property-tax rate, ' 'color nitric oxides concentration', render_method='bruteforce', **PLOT_DEFAULTS) add_axes(scatter_plot, x_label='Percent lower status in the population', y_label='Median house prices') return scatter_plot
from traits.has_traits import HasTraits from traits.trait_types import Int, Any, File from pyface.api import clipboard from traitsui.editors.file_editor import FileEditor from traitsui.group import VGroup from traitsui.item import Item from traitsui.menu import OKCancelButtons from traitsui.view import View import os.path import numpy as np import chaco.default_colormaps as dc CLASS_COLORS = dc.RdYlGn(DataRange1D(low=-0.1, high=1.1)) ANNOTATOR_COLORS = dc.gist_ncar(DataRange1D(low=-0.1, high=1.1)) def get_annotator_color(idx): nannotators = 8 idx %= nannotators color_idx = ANNOTATOR_COLORS.map_index(np.array(float(idx) / nannotators)) return list(ANNOTATOR_COLORS.color_bands[color_idx]) def get_class_color(idx): nclasses = 8 idx %= nclasses color_idx = CLASS_COLORS.map_index(np.array(float(idx) / nclasses)) return list(CLASS_COLORS.color_bands[color_idx])
def _1D_mapper(source): data_range = DataRange1D() data_range.add(source) return LinearMapper(range=data_range)
def __init__(self, *args, **kw): super(LumenDetector, self).__init__(*args, **kw) self._color_mapper = hot(DataRange1D(low=0, high=1))
def create_plot(self): if hasattr(self.value, 'shadows'): color_gen = color_generator() shadowcolors = {} for shadow in self.value.shadows: shadowcolors[shadow] = color_gen.next() container_class = { 'h': HPlotContainer, 'v': VPlotContainer }[self.orientation] container = container_class(spacing=15, padding=15, bgcolor='transparent') container.fill_padding = True container.bgcolor = (236 / 255.0, 233 / 255.0, 216 / 255.0) if self.show_all: self.plot_items = self.value.keys() if len(self.plot_items) > 0: plot_configs = [] for (plot_num, var_name) in enumerate(self.plot_items): if not (isinstance(self.value[var_name], ndarray) and \ len(self.value[var_name].shape) == 1): continue plot_configs.append( PlotConfig(x=var_name + '_index', y=var_name, type='Line', number=plot_num)) self.plot_configs = plot_configs if len(self.plot_configs) > 0: number_to_plots = {} for plot_config in self.plot_configs: plotlist = number_to_plots.get(plot_config.number, []) plotlist.append(plot_config) number_to_plots[plot_config.number] = plotlist keys = number_to_plots.keys() keys.sort() container_list = [number_to_plots[number] for number in keys] for plot_group in container_list: context_adapter = PlotDataContextAdapter(context=self.value) plot = Plot(context_adapter) plot.padding = 15 plot.padding_left = 35 plot.padding_bottom = 30 plot.spacing = 15 plot.border_visible = True for plot_item in plot_group: if len(self.value[plot_item.y].shape) == 2: color_range = DataRange1D( low=min(self.value[plot_item.y]), high=max(self.value[plot_item.y])) plot.img_plot(plot_item.y, colormap=gray(color_range), name=plot_item.y) else: plot_type = { 'Line': 'line', 'Scatter': 'scatter' }[plot_item.type] plot.plot( (plot_item.x, plot_item.y), name=plot_item.x + " , " + plot_item.y, color=(.7, .7, .7), type=plot_type, ) if plot.index_axis.title != '': plot.index_axis.title = plot.index_axis.title + ', ' + plot_item.x else: plot.index_axis.title = plot_item.x if plot.value_axis.title != '': plot.value_axis.title = plot.value_axis.title + ', ' + plot_item.y else: plot.value_axis.title = plot_item.y if self.view_shadows and hasattr( self.value, 'shadows'): self.generate_shadow_plots(plot, shadowcolors, plot_item, plot_type) plot.tools.append(PanTool(plot)) container.add(plot) self.plot = container