def _call(self, dmaps): # NOTE: workaround to overlay drawingtool. does not work if overlayed after Overlay + collate # similar to reported holoviews bug. tap stream attached to a dynamic map does not update # https://github.com/holoviz/holoviews/issues/3533 extra_overlays = dmaps[len(self.channel_viewers):] out_dmaps = [] if self.composite_channels: composite_dmaps = [ ch_viewer(dmap) for (key, ch_viewer ), dmap in zip(self.channel_viewers.items(), dmaps) if key in self.composite_channels ] if len(composite_dmaps) > 0: composite_dmap = hv.Overlay(composite_dmaps).collate() out_dmaps.append(composite_dmap.apply(blend_overlay)) if self.overlay_channels: out_dmaps.extend([ ch_viewer(dmap) for (key, ch_viewer ), dmap in zip(self.channel_viewers.items(), dmaps) if key in self.overlay_channels ]) out_dmaps.extend(extra_overlays) return hv.Overlay(out_dmaps).collate().relabel(group='segmentation')
def visualize_scene(self, scene): """ Threshold prediction and figure generation """ scene_data = self.data[self.data.scene == scene] model_names = ['KMeans', 'GMM', 'SSC'] batches = set(scene_data.batch) batches.add('global') for batch in batches: for m in model_names: self.threshs = self.threshs.append( { 'batch': batch, 'scene': scene, 'model': m }, ignore_index=True) scene_scatters = [] feature = (self.marker_pairs[0][0].split('_')[1] + '_' + self.marker_pairs[0][0].split('_')[2]) for marker_pair in self.marker_pairs: if (marker_pair[0].split('_')[1] + '_' + marker_pair[0].split('_')[2]) != feature: if self.save_figs: self.save_thresh_figs(scene_scatters, str(scene), self.save_dir, feature) scene_scatters = [] print( str(self._counter) + '/' + str(437 * 9) + ': Processing scene = ' + str(scene) + ', batch = ' + 'global' + ' and marker_pair = ' + str(marker_pair)) global_scatter, global_curves = self.get_marker_pair_thresh( scene_data, scene, marker_pair, 'global') for batch in set(scene_data.batch): print( str(self._counter) + '/' + str(437 * 9) + ': Processing scene = ' + str(scene) + ', batch = ' + str(batch) + ' and marker_pair = ' + str(marker_pair)) self._counter += 1 batch_scene_data = scene_data[scene_data.batch == batch] local_scatter, local_curves = self.get_marker_pair_thresh( batch_scene_data, scene, marker_pair, batch) scene_scatters.append(global_scatter * local_scatter * hv.Overlay(local_curves) * hv.Overlay(global_curves)) feature = (marker_pair[0].split('_')[1] + '_' + marker_pair[0].split('_')[2])
def changeBaseMap(self): if self.overlays and len(self.overlays) > 1: # on change le flux WMTS et on reprend la couche l'entité (la plus haute de la pile) self.baseTileMap = [ ts() for name, ts in hv.element.tiles.tile_sources.items() if name == self.fond_de_carte ][0] allLayers = self.getAllLayersWithoutBaseMap() self.overlays = hv.Overlay() * self.baseTileMap self.overlays.update(allLayers) else: # on charge le flux WMTS self.overlays = hv.Overlay() * [ ts() for name, ts in hv.element.tiles.tile_sources.items() if name == self.fond_de_carte ][0]
def GenDepth(sonar_data, chan_id, regen_cache=False): normalized_channel = NormalizeChannel(sonar_data, chan_id, regen_cache=regen_cache) hv_ds = holoviews.Dataset(normalized_channel) img = hv_ds.to(holoviews.Image, kdims=["frame_index", "depth"]) img = img.opts(cmap='viridis', logz=False) img = img.opts(tools=['hover', 'crosshair']) channel = sonar_data.sel(channel=chan_id) depth_data = holoviews.Table((channel.frame_index, channel.water_depth), 'frame_index', 'depth') depth_curve = holoviews.Curve(depth_data) depth_curve = depth_curve.opts(line_width=0.5, color='red', alpha=0.5) #, line_dash='dashed') depth_curve = depth_curve.opts(tools=['hover', 'crosshair']) depth_curve = depth_curve.opts(active_tools=['box_zoom']) # @todo We should consider using the native height instead of 1024 as we will see more detail. #y_size = len(normalized_channel.depth) x_size = 1024 y_size = 768 rasterized_img = holoviews.operation.datashader.rasterize(img, width=x_size, height=y_size, precompute=True) rasterized_img = rasterized_img.opts(invert_yaxis=True) graph = holoviews.Overlay([rasterized_img, depth_curve]) graph = graph.collate() return graph
def display(self, trackqc: Union[pd.DataFrame, TrackQC]) -> hv.Overlay: "Scatter plot showing the evolution of the nb of missing, fixed and no-errors beads." frame = self.dataframe(trackqc) total = len(trackqc.status.index) for i in self.params: if i in frame: frame[i] *= 100 / total hover = HoverTool(tooltips=self.tooltips) crvs: List[hv.Element] = [] for tpe, opts in zip((hv.Points, hv.Curve), (self.ptsstyle, {})): opts = { 'tools': [hover], **cast(dict, opts), **cast(dict, self.styleopts) } crvs.extend( tpe(frame, kdims=['date', i], label=i).options(color=j, **opts) for i, j in zip(self.params, self.colors) if i in frame) def _newaxis(plot, _): plot.state.extra_x_ranges = { "track": FactorRange(*frame.track.values) } plot.state.add_layout(CategoricalAxis(x_range_name="track"), 'above') return (hv.Overlay(crvs).redim.range(y=(0, 100)).redim.label( x=self.xlabel, ok=self.ylabel.format(total=int(total))).options( finalize_hooks=[_newaxis]).clone(label=self.title))
def plot_task_signals(self, task: TaskID, signals: TypedList[str] = ['util', 'load']): """ Plot the task-related load-tracking signals :param task: The name or PID of the task, or a tuple ``(pid, comm)`` :type task: str or int or tuple :param signals: List of signals to plot. :type signals: list(str) """ window = self.trace.window task = self.trace.get_task_id(task, update=False) def _plot_signal(signal): df = self.df_task_signal(task, signal) df = df_refit_index(df, window=window) return plot_signal( df[signal], name=signal, ).options(dict(Curve=dict(alpha=0.5)), ) return hv.Overlay([_plot_signal(signal) for signal in signals] + [self._plot_overutilized()]).options( title=f'Load-tracking signals of task {task}', ylabel='/'.join(sorted(signals)), )
def react_to_tap(x, y): if x is not None and y is not None and x < 5. and y < 5.: del l1[4:] # temorary hack: want a reset button later append_euler_plots(l1, (x, y), funcs[self.function_]) return hv.Overlay(l1).redim.range( x=(-5, 5), y=(-5, 5)).options(**pos_opts).relabel(self.function_)
def plot_arm_boundaries(self, time=None, plt_range=None, x_range=None, y_range=None): if time is None: time = self.posteriors.get_time_start() if plt_range is None: plt_range = self.posteriors.get_time_total() if x_range is None: x_range = (time, time + plt_range) if y_range is None: y_range = self.posteriors.get_pos_range() lines = hv.Overlay() for arm in self.enc_settings.arm_coordinates: for bound in arm: line = hv.Curve((x_range, [bound] * 2), extents=(x_range[0], None, x_range[1], None), group='arm_bound').opts( style={ 'color': '#AAAAAA', 'line_dash': 'dashed', 'line_color': 'grey', 'linestyle': '--' }) lines *= line return lines
def view( self, ch_to_display, scalebar_size, rescale_factor, show_legend=True, legend_position="bottom_left", ): w = self.data.sizes["x"] h = self.data.sizes["y"] self.prepare_data(ch_to_display) self.combine_ch_colors() self.prepare_texts(ch_to_display) self.rangexy = hv.streams.RangeXY(source=self.rendered_image) self.scalebar_size = scalebar_size self.regridded_image = ( regrid(self.rendered_image, streams=[self.rangexy]) .options(framewise=True) .opts(width=int(w / rescale_factor), height=int(h / rescale_factor)) ) self.scalebar_image = self.regridded_image * hv.DynamicMap( self.scalebar, streams=[self.rangexy] ) self.overlay_image = hv.Overlay([self.scalebar_image] + self.captions_legend) self.final_image = self.overlay_image.collate().opts( show_legend=show_legend, legend_position=legend_position ) return self.final_image
def plot_gain_chart(target, predict, num_buck=10): """ Строит gain_chart по истиным и предсказанным меткам На первом шаге бьет наблюдения на бакеты, затем считает средний bad_rate. На втором шаге строится график, где кривая обозначает предсказанное значение целевой переменной, столбцы - истинные. Parameters ---------- target - истинные значения целевой переменной predict - предсказания вероятности num_buck - количество бакетов """ data = pd.DataFrame({'target': target, 'predict': predict}) H = HL(target, predict, num_buck) data = (data.assign( bucket=np.ceil(data['predict'].rank(pct=True) * num_buck)).assign( obj_cnt=1).groupby('bucket').agg({ 'target': 'sum', 'predict': 'mean', 'obj_cnt': 'sum' }).assign(bad_rate=lambda x: x.target / x.obj_cnt).reset_index()) bars_gain = hv.Bars(data, kdims=['bucket'], vdims=['bad_rate'], label='observed') \ .opts(plot={'xrotation': 90, 'show_legend': True}, style={'color': 'yellow'}) curve_gain = hv.Curve(data, kdims=['bucket'], vdims=['predict'], label='predicted') \ .opts(plot={'xrotation': 90, 'show_legend': True}, style={'color': 'black'}) return hv.Overlay([bars_gain, curve_gain]).redim.label(**{'target': 'Bad Rate'})\ .relabel(f'HL_score = {H}').opts(plot={'legend_position': 'top_left'})
def create_density_plots(df, density, kdims, cmap): cm = {} if density == 'all': dfs = {_sentinel: df} elif density == 'group': if 'z' not in df.columns: warnings.warn( f'`density=\'groups\' was specified, but no group found. Did you specify `color=...`?' ) dfs = {_sentinel: df} elif not is_categorical(df['z']): warnings.warn( f'`density=\'groups\' was specified, but column `{condition}` is not categorical.' ) dfs = {_sentinel: df} else: dfs = {k: v for k, v in df.groupby('z')} cm = cmap else: raise ValueError( f'Invalid `density` type: \'`{density}`\'. Possible values are `\'all\'`, `\'group\'`.' ) # assumes x, y order in kdims return [ hv.Overlay([ hv.Distribution(df, kdims=dim).opts(color=cm.get(k, 'black'), framewise=True) for k, df in dfs.items() ]) for dim in kdims ]
def _plot(self, label, method_name, logx=False, logy=False, data_color=None, fit_color=None, xlabel='value'): import holoviews as hv import easier as ezr if data_color is None: data_color = ezr.cc[0] if fit_color is None: fit_color = ezr.cc[1] func = getattr(self.dist, method_name) hist_func = getattr(self.hist_dist, method_name) c1 = hv.Curve( (self.x, 1e-9 + func(self.x)), xlabel, 'Density', label=f'{self.dist.dist.name} Fit').options(logx=logx, logy=logy, color=fit_color) c2 = hv.Curve((self.x, 1e-9 + hist_func(self.x)), label=f'{label} Empirical').options(color=data_color) return hv.Overlay([c1, c2]).options(legend_position='top')
def make_density_plot(user, filter_date_from,filter_date_to): heartbeats = pd.DataFrame.from_records( self.client.smartsleep.heartbeats.find({"userId":user}) ) sleeps = pd.DataFrame.from_records( self.client.smartsleep.sleeps.find({"userId":user}) ) parts = [] if not heartbeats.empty: heartbeats['time'] = pd.DatetimeIndex( heartbeats['time']) + timedelta(hours=1,minutes=0 ) heartbeats = heartbeats[heartbeats.time >= filter_date_from] heartbeats = heartbeats[heartbeats.time <= filter_date_to] if not heartbeats.empty: parts.append(hv.Spikes(heartbeats.time, label="heartbeats"). opts(spike_length=1,color="red").opts(tools=['hover'])) if not sleeps.empty: sleeps['time'] = pd.DatetimeIndex(sleeps['time']) + timedelta(hours=1,minutes=0) sleeps = sleeps[sleeps.time >= filter_date_from] sleeps = sleeps[sleeps.time <= filter_date_to] if not sleeps.empty: if sleeps.sleeping.any(): parts.append(hv.Spikes(sleeps[sleeps.sleeping].time, label="screen off").opts( spike_length=1,color="blue").opts(tools=['hover'])) if (~sleeps.sleeping).any(): parts.append(hv.Spikes(sleeps[~sleeps.sleeping].time,label="screen on").opts( spike_length=1,color="green").opts(tools=['hover'])) print(f'{sleeps.shape[0]} sleeps') print(f'{heartbeats.shape[0]} heartbeats') return hv.Overlay(parts).opts(width=900,height=300, legend_position='top_left', toolbar='above', yaxis=None, padding=0.1 )
def plot_ripple_all(self, rip_ind): rip_plt = self.plot_ripple(rip_ind) x_range = rip_plt.range(self.time_dim_name) y_range = rip_plt.range(self.pos_dim_name) arm_plt = self.plot_arm_boundaries(time=x_range[0], x_range=x_range, y_range=y_range) lin_plt = self.plot_ripple_linflat(rip_ind) return hv.Overlay([rip_plt, arm_plt, lin_plt], label='ripple_decode: ', group=str(rip_ind))
def histogram_plot(self, xtrack=None, atrack=None, x=None, y=None): """plot histogram at xtrack, atrack""" if x is not None: xtrack = x if y is not None: atrack = y # atrack and xtrack are from mouse or user. get the nearest where histogram is defined xtrack, atrack = self._get_xatrack(xtrack=xtrack, atrack=atrack) # get histogram hist_at = self.gradients_hist.sel(atrack=atrack, xtrack=xtrack, method='nearest', tolerance=500) hp_list = [] for sel_one2D in self.combine_all: hist2D_at = hist_at.sel(sel_one2D) hist2D360 = circ_hist(hist2D_at['weight']) style = self._get_style(hist2D_at) hp_list.append( hv.Path(hist2D360, kdims=['xtrack_g', 'atrack_g']).opts(axiswise=False, framewise=False, aspect='equal', **style)) return hv.Overlay(hp_list).opts(xlabel='xtrack %d' % xtrack, ylabel='atrack %d' % atrack, width=200, height=200)
def plot_cpu(cpu): name = f'CPU{cpu} util' series = util_df[cpu].copy(deep=False) series.index.name = 'Time' series.name = name fig = plot_signal(series).options( 'Curve', ylabel='Utilization', ) # The "y" dimension has the name of the series that we plotted fig = fig.redim.range(**{name: (-10, 1034)}) times, utils = zip(*series.items()) fig *= hv.Overlay([ hv.VSpan(start, end).options( alpha=0.1, color='grey', ) for util, start, end in zip( utils, times, times[1:], ) if not util ]) return fig
def mark_color_3d_plot(self, elevation, azimuth, col1='c00', col2='c01', col3='c02'): hv.output(backend='matplotlib') scatter = [ hv.Scatter3D(mark_pos.loc[:, [col1, col2, col3]]).opts( dict(Scatter3D=dict(bgcolor='black', s=3))) for elec_id, mark_pos in self.unit_spks.items() ] overlay = hv.Overlay(scatter, label='Plot of spikes and their features ' + col1 + ', ' + col2 + ', and ' + col3) overlay = overlay.opts({ 'Scatter3D': { 'plot': { 'fig_size': 400, 'azimuth': int(azimuth), 'elevation': int(elevation) }, 'norm': { 'framewise': True } } }) return overlay
def plot_qq(self, label='', logx=False, logy=False, data_color=None, fit_color=None): """ Make a q-q plot. X axis will hold theoretical quantiles, Y axis the impirircal """ import holoviews as hv import numpy as np if data_color is None: data_color = 'blue' if fit_color is None: fit_color = 'red' q_data_fit = np.polyval([self._a, self._b], self.q_theory) c1 = hv.Scatter((self.q_theory, self.q_data), 'Theoretical Quantiles', 'Empirical Quantiles', label=label).options(size=5, alpha=.5, color=data_color, logx=logx, logy=logy) label = f'{self.dist.dist.name} params = {["%0.4g" % p for p in self.dist_params]}'.replace( "'", "") c2 = hv.Curve((self.q_theory, q_data_fit), label='Best Fit Line').options(color=fit_color, alpha=.2) c3 = hv.Curve((self.q_theory, self.q_theory), label=label).options(color='green', alpha=.2) return hv.Overlay([c1, c2, c3]).options(legend_position='top')
def react_to_tap(x, y): if x is not None and y is not None and x < 5. and y < 5.: # Avoids firing when clicked on a legend del l1[4:] # temorary hack: want a reset button later append_euler_plots(l1, (x, y), funcs[func_sel]) return hv.Overlay(l1).redim.range( x=(-5, 5), y=(-5, 5)).options(**pos_opts).relabel(func_sel)
def _season_vlines(): season_vlines = hv.Overlay( [hv.VLine(pd.to_datetime(season_start).dayofyear) .options(line_width=1.5, alpha=0.9, color=color, line_dash='dotted') for season_start, color in SEASON_STARTS.items()] ) return season_vlines
def show(self, **kwargs): width = kwargs.get("width", 800) height = kwargs.get("height", 600) opts.defaults(opts.WMTS(width=width, height=height)) tile = gv.WMTS("https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png") ps = [tile] # external ds = self._obj.loc["line0"] ds = ds.append(ds.iloc[0]).reset_index(drop=True) dland = ds.loc[ds.tag == "land"] dland_ = np.split(dland, np.flatnonzero(np.diff(dland.index) != 1) + 1) for seg in dland_: ps.append( seg.hvplot.paths(x="lon", y="lat", geo=True, color="brown")) dwater = ds.loc[ds.tag == "open"] dwater_ = np.split(dwater, np.flatnonzero(np.diff(dwater.index) != 1) + 1) for seg in dwater_: ps.append( seg.hvplot.paths(x="lon", y="lat", geo=True, color="blue")) # islands for line in self._obj.index.levels[0][1:]: ds = self._obj.loc[line] ds = ds.append(ds.iloc[0]).reset_index(drop=True) ps.append( ds.hvplot.paths(x="lon", y="lat", geo=True, color="green")) return hv.Overlay(ps)
def isotonic(df, predict, target, calibrations_data=None): """Визуализация точности прогноза вероятности **Аргументы** df : pandas.DataFrame таблица с данными predict : str прогнозная вероятность target : str бинарная (0, 1) целевая переменная calibrations_data : pandas.DataFrame таблица с калибровками **Результат** area * curve * [curve] : holoviews.Overlay """ df_agg = _aggregate_data_for_isitonic(df, predict, target) confident_intervals = hv.Area(df_agg, kdims=['predict'], vdims=['ci_l', 'ci_h'], group='Confident Intervals') curve = hv.Curve(df_agg, kdims=['predict'], vdims=['isotonic'], group='Isotonic') if calibrations_data is not None and target in calibrations_data.columns: calibration = hv.Curve(data=calibrations_data[['predict', target]].values, kdims=['predict'], vdims=['target'], group='Calibration', label='calibration') return hv.Overlay(items=[curve, confident_intervals, calibration], group='Isotonic', label=predict) return hv.Overlay(items=[curve, confident_intervals], group='Isotonic', label=predict)
def plot_cpu(cpu): return hv.Overlay( [_plot_signal(cpu=cpu, signal=signal) for signal in signals] + [ self.ana.cpus.plot_orig_capacity(cpu), plot_capacity(cpu), self._plot_overutilized() ]).options(title=f'CPU{cpu} signals', )
def plot_observ_func(self, bin): plot_list = [] plot_aspect = 10 sel_observ = self.observ.query('dec_bin == @bin') sel_plot_observ = sel_observ.get_distribution_view() sel_max_observ = sel_plot_observ.max().max() sel_pos = sel_observ['position'] sel_like = self.likelihoods.query('dec_bin == @bin') sel_plot_like = sel_like.get_distribution_view() sel_max_like = sel_plot_like.max().max() sel_post = self.posteriors.query('dec_bin == @bin') sel_plot_post = sel_post.get_distribution_view() sel_max_post = sel_plot_post.max().max() sel_post_prev = self.posteriors.query('dec_bin == @bin-1') sel_plot_post_prev = sel_post_prev.get_distribution_view() sel_max_post_prev = sel_plot_post_prev.max().max() for ii in range(len(sel_observ)): sel = sel_plot_observ.iloc[ii] plot_list.append( hv.Curve(sel, vdims='observ', label=str(ii)).opts(labelled=['y'], ylim=(0, sel_max_observ))) plot_list.append( hv.Points((sel_pos.iloc[ii], [sel_max_observ / 10]))) if len(sel_observ) == 0: plot_list.append( hv.Curve([0, 0], vdims='observ', label='N/A').opts(labelled=['y'], ylim=(0, sel_max_observ), xaxis=None)) plot_list.append( hv.Points((sel_like['position'], [0]), vdims='observation')) like_plot = (hv.Curve(sel_plot_like.iloc[0], vdims='like').opts(labelled=['y'], ylim=(0, sel_max_observ), xaxis=None)) post_overlay = ( hv.Curve(sel_plot_post.iloc[0], vdims='post', label='cur') * hv.Curve(sel_plot_post_prev.iloc[0], vdims='post', label='prev')) return (hv.Overlay( plot_list, label=f'Spks: {len(sel_observ)} ({self.indic_str})').opts( aspect=plot_aspect) + like_plot + post_overlay).cols(1).opts( hv.opts.Curve(framewise=True, xlim=(0, None), ylim=(0, None), yformatter=self.yfmt, aspect=plot_aspect, yticks=2), hv.opts.Points(framewise=True, xlim=(0, None), ylim=(0, None), yformatter=self.yfmt, aspect=plot_aspect, yticks=2))
def parallel_coordinates(data, class_column, cols=None, alpha=0.5, width=600, height=300, var_name='variable', value_name='value', **kwds): """ Parallel coordinates plotting. Parameters ---------- frame: DataFrame class_column: str Column name containing class names cols: list, optional A list of column names to use alpha: float, optional The transparency of the lines Returns ------- obj : HoloViews object The HoloViews representation of the plot. See Also -------- pandas.plotting.parallel_coordinates : matplotlib version of this routine """ # Transform the dataframe to be used in Vega-Lite if cols is not None: data = data[list(cols) + [class_column]] cols = data.columns df = data.reset_index() index = (set(df.columns) - set(cols)).pop() assert index in df.columns df = df.melt([index, class_column], var_name=var_name, value_name=value_name) labelled = [] if var_name == 'variable' else ['x'] if value_name != 'value': labelled.append('y') options = { 'Curve': dict(kwds, labelled=labelled, alpha=alpha, width=width, height=height), 'Overlay': dict(legend_limit=5000) } colors = _hv.plotting.util.process_cmap('Category10', categorical=True) dataset = _hv.Dataset(df) groups = dataset.to(_hv.Curve, var_name, value_name).overlay(index).items() return _hv.Overlay([ curve.relabel(k).options('Curve', color=c) for c, (k, v) in zip(colors, groups) for curve in v ]).options(options)
def combined(self, lon, lat): """Combines the temperature and precipitation holoviews objects. Parameters ---------- lon : int or float The longitutde of the point. lat : int or float The latitude of the point. Returns ------- out : holoviews Layout or Overlay Layout or overlay depends on how the object was initialized. Raises ------ ValueError If either longitude or latitude or both are out of bounds. See Also -------- out_of_bounds : Checks if longitude and latitude are out of bounds. """ out_of_bounds(lon, lat, 'ClimvisHVPlot.combined') self.reinitialize(lon, lat, self._overlay) real_coords = real_lon_lat(lon, lat) real_lon = real_coords['lon'] real_lat = real_coords['lat'] # Creating the holoviews Curve and Bars objects for temperature and # precipitation respectively tmp = hv.Curve(annual_cycle_for_hv(lon, lat, variable='tmp'), label='Real lon, lat: {} {}'.format( real_lon, real_lat)).opts(color='red', tools=['hover']) pre = hv.Bars(annual_cycle_for_hv( lon, lat, variable='pre'), ).opts(tools=['hover']) # Formatting xlables and ylabels if self._overlay: out = hv.Overlay([pre, tmp.relabel('')], label='Real lon, lat: {} {}'.format( real_lon, real_lat)) out.opts(xlabel='Month', ylabel='Prec. and Temp. ' '(°C and mm mth^-1)') else: out = hv.Layout([ tmp.opts(xlabel='Month', ylabel='Temperature (°C)'), pre.opts(xlabel='Month', ylabel='Precipitation (mm mth^-1)') ]) return out
def andrews_curves(data, class_column, samples=200, alpha=0.5, width=600, height=300, cmap=None, colormap=None, **kwds): """ Andrews curve plot. Parameters ---------- frame: DataFrame class_column: str Column name containing class names samples: int, optional Number of samples to draw alpha: float, optional The transparency of the lines cmap/colormap: str or colormap object Colormap to use for groups Returns ------- obj : HoloViews object The HoloViews representation of the plot. See Also -------- pandas.plotting.parallel_coordinates : matplotlib version of this routine """ t = np.linspace(-np.pi, np.pi, samples) vals = data.drop(class_column, axis=1).values.T curves = np.outer(vals[0], np.ones_like(t)) for i in range(1, len(vals)): ft = ((i + 1) // 2) * t if i % 2 == 1: curves += np.outer(vals[i], np.sin(ft)) else: curves += np.outer(vals[i], np.cos(ft)) df = pd.DataFrame({'t': np.tile(np.arange(samples), curves.shape[0]), 'sample': np.repeat(np.arange(curves.shape[0]), curves.shape[1]), 'value': curves.ravel(), class_column: np.repeat(data[class_column], samples)}) labelled = ['x'] options = {'Overlay': dict(legend_limit=5000), 'Curve': dict(kwds, labelled=labelled, alpha=alpha, width=width, height=height, **kwds)} dataset = hv.Dataset(df) groups = dataset.to(hv.Curve, 't', 'value').overlay('sample').items() if cmap and colormap: raise TypeError("Only specify one of `cmap` and `colormap`.") cmap = cmap or colormap or cc.palette['glasbey_category10'] colors = hv.plotting.util.process_cmap(cmap, categorical=True, ncolors=len(groups)) return hv.Overlay([curve.relabel(k).options('Curve', color=c) for c, (k, v) in zip(colors, groups) for curve in v]).options(options)
def __init__(self, **params): super(BaseMapApp, self).__init__(**params) # on surcharge l overlays du parent avec le fond de carte self.baseTileMap = [ ts() for name, ts in hv.element.tiles.tile_sources.items() if name == self.fond_de_carte ][0] self.overlays = hv.Overlay() * self.baseTileMap
def get_plot(self): items = [view.get_plot() for view in self.views] plot = hv.Overlay(items).collate( ) # todo is collate always needed? Does it always return a DynamicMap? -> generalize if self.opts_dict: plot = plot.apply.opts(**self.opts_dict) return plot
def beta_plots( wins: Iterable, losses: Iterable, labels: Iterable, legend_position='right', alpha=.5, normed=False, xlabel=None, ylabel=None): """ Make beta plots for win/loss type scenarios. The wins/losses are provided in arrays. Each element of the array corresponds to a specific win/loss scenario you want plotted. So, to just determine the beta distirbution of a single scenario, these should be one-element arrays. Args: wins: the number of "wins" losses: the number of "losses" labels: The label for each scenario legend_postion: Where to put the legend alpha: the opacity of the area plots xlabel: The x label [default "Win Perdentage"] ylabel: The y label [default, "Density"] """ from scipy.stats import beta import numpy as np import holoviews as hv if xlabel is None: xlabel = 'Win Percentage' if ylabel is None: ylabel = 'Density' c_list = [] x = np.linspace(0, 1, 500) xpoints = [] ypoints = [] for (won, lost, label) in zip(wins, losses, labels): dist = beta(won + 1, lost + 1) y = dist.pdf(x) if normed: y_max = np.max(y) else: y_max = 1. y = y / y_max win_frac = won / (won + lost + 1e-12) xpoints.append(win_frac * 100) ypoints.append(dist.pdf(win_frac) / y_max) c = hv.Area((100 * x, y), xlabel, ylabel, label=label).options(alpha=alpha) c_list.append(c) c1 = hv.Overlay(c_list).options(legend_position='right') c2 = hv.Scatter((xpoints, ypoints), xlabel, ylabel).options(color='black', size=8, tools=['hover']) return (c1 * c2).options(legend_position=legend_position)