def generateHoloview(self, df, SSC, FSC, type, counter_max=50): renderer = hv.renderer('bokeh') body_points = hv.Scatter(df, SSC, FSC).opts(color='r', title='SSC vs FSC Default Gating') body_hist = body_points.hist(num_bins=50, dimension=[SSC, FSC]) body = body_hist counter = 0 for index in range(len(df.columns)): for index2 in range(index+1, len(df.columns)): col = df.columns[index] col2 = df.columns[index2] if col2 != col and col not in (SSC, FSC) and col2 not in (SSC, FSC) and counter < counter_max: points = hv.Scatter(df, col, col2) hist = points.hist(num_bins=50, dimension=[col, col2]) body += hist counter += 1 print(counter) try: body = body.opts( opts.Scatter(tools=['box_select', 'lasso_select']), opts.Layout(shared_axes=True, shared_datasource=True)).cols(2) except: body = body.opts( opts.Scatter(tools=['box_select', 'lasso_select']), opts.Layout(shared_axes=True, shared_datasource=True)) renderer.save(body, os.path.join(self.directory, str(type)+"gating"))
def plotSpectrum(self, plotLog=True, aduRange=[], ROI=None): if len(aduRange) == 0: aduRange = [0.1, 700] elif len(aduRange) == 1: aduRange = [0.1, aduRange[0]] elif len(aduRange) == 2: aduRange = [aduRange[0], aduRange[1]] if ROI is None: dadu = self.__dict__['adu'] else: dadu = self.__dict__['adu'] dx = self.__dict__['x'].flatten() dy = self.__dict__['y'].flatten() inROIx = np.logical_and(dx > np.array(self.ROI).flatten()[0], dx < np.array(self.ROI).flatten()[1]) inROIy = np.logical_and(dy > np.array(self.ROI).flatten()[2], dy < np.array(self.ROI).flatten()[3]) inROI = np.logical_and(inROIx, inROIy) dadu = dadu.flatten()[inROI] hst = np.histogram(dadu, np.arange(aduRange[0], aduRange[1])) if self._plotWith == 'matplotlib': if plotLog: plt.semilogy(hst[1][1:], hst[0], 'o') else: plt.plot(hst[1][1:], hst[0], 'o') elif self._plotWith == 'holoviews': if plotLog: return hv.Scatter( (hst[1][1:], np.log(hst[0]))) #,'ADU','log_nDrops') else: return hv.Scatter((hst[1][1:], hst[0])) #,'ADU','nDrops') else: return hst
def get_plot(ticker, date_range, log_scale): df = pd.read_csv(Input_csv_flename, skiprows=1) df['date'] = pd.to_datetime(df['date']) print('log scale switch= ', log_scale) print('ticker selection = ', ticker) # Load and format the data # create date filter using values from the range slider # store the first and last date range slider value in a var start_date = date_range_slider.value[0] end_date = date_range_slider.value[1] # create filter mask for the dataframe mask = (df['date'] > start_date) & (df['date'] <= end_date) df = df.loc[mask] # filter the dataframe # create the Altair chart object semilogy1 = hv.Scatter(df, ['date', ticker], vdims=['date', ticker]).opts(tools=['hover', 'crosshair'], logy=log_scale) # semilogy2 = hv.Scatter(df,['date','MiddleSex'], label='MiddleSex').opts(logy=log_scale) # semilogy3 = hv.Scatter(df,['date','Massachusetts'], label='Massachusetts').opts(logy=log_scale) #chart = alt.Chart(df).mark_line().encode(x='date', y='Confirmed Cases', tooltip=alt.Tooltip(['date','price'])).transform_filter( # (datum.symbol == ticker) # this ties in the filter semilogy1.opts(logy=log_scale, width=800, height=600, xlabel='Date', ylabel='Confirmed Cases', show_grid=True, size=5, padding=0.1, line_width=5, legend_position='top_left') # also show daily increasement temp_diff = np.diff(df[ticker]) daily_increase = np.append([0], temp_diff) # daily_data =pd.DataFrame() # daily_data['date'] = df['date'] # daily_data['di'] = daily_increase # table = hv.Table((df['date'], daily_increase), 'date', 'daily_increase') df['di'] = daily_increase # barplot = hv.Bars(table).opts(width=800,height=200,xlabel='Date',ylabel='Daily Increase', show_grid=True,color="red") barplot = hv.Scatter(df, ['date', 'di'], vdims=['date', 'di']).opts(tools=['hover', 'crosshair'], width=800, height=200, xlabel='Date', ylabel='Daily Increment', show_grid=True, size=5, padding=0.1, line_width=5, color="red") curveplot = hv.Curve(df, ['date', 'di']).opts(color="green") return pn.Column(semilogy1, barplot * curveplot)
def plot_curve(): df = download_data(index.value) future_df = download_data_predicted(index.value) title = index.value + " Exchange Rate" # Create stock curve past_label = "Past " + title future_label = "Predicted Future " + title df['label'] = past_label future_df['label'] = future_label new_df = pd.concat([df, future_df], axis=0) curve = hv.Curve(df, 'Date', ('Close', 'label')) curve_pred = hv.Curve(future_df, 'Date', ('Close', 'Price')) # Labels and layout tgt = curve.relabel("Past " + title).opts( #width=width, height=600, show_grid=True, labelled=['y'], default_tools=[hover], hooks=[set_tools], title=title, responsive=True) tgt_pred = curve_pred.relabel("Future " + title).opts( #width=width, height=600, show_grid=True, labelled=['y'], default_tools=[hover], hooks=[set_tools], title=title, responsive=True) src = curve.opts(height=100, yaxis=None, default_tools=[], color='green', responsive=True) src_pred = curve_pred.opts(height=100, yaxis=None, default_tools=[], color='green', responsive=True) circle = hv.Scatter(df, 'Date', ('Close', 'Price')).opts(color='green') circle_pred = hv.Scatter(future_df, 'Date', ('Close', 'Price')).opts(color='blue') RangeToolLink(src, tgt) # Merge rangetool layout = ((tgt * tgt_pred * circle * circle_pred) + (src * src_pred)).cols(1) layout.opts(opts.Layout(shared_axes=False, merge_tools=False), opts.Curve(toolbar=None), opts.Scatter(size=3)) print("kepanggil nih viz") print(df["Close"][0]) print(index.value) return layout
def generateCombined(self, decimated, SSC, FSC, cachebust, counter_max=20): renderer = hv.renderer('bokeh') body = None points = None point_collect = [] for key in decimated.keys(): print(key) point = hv.Scatter(decimated[key], SSC, FSC, label=key) point_collect.append(point) if points is None: points = point else: points *= point if body is None: body = points.opts(title='Default {0}: SSC vs FSC'.format("Combined"), height=450, width=450) else: body += points.opts(title='Default {0}: SSC vs FSC'.format("Combined")) for dim in (SSC, FSC): hists = None for point in point_collect: hist = histogram(point, dimension=dim) if hists is None: hists = hist else: hists *= hist body += hists potentialCols = [c for c in decimated[list(decimated.keys())[0]].columns if c != SSC and c != FSC] for i in range(len(potentialCols)): for j in range(i+1, len(potentialCols)): points = None point_collect = [] for key in decimated.keys(): point = hv.Scatter(decimated[key], potentialCols[i], potentialCols[j], label=key) point_collect.append(point) if points is None: points = point else: points *= point body += points.opts(title='Combined: {0} vs {1}'.format(potentialCols[i], potentialCols[j]), height=450, width=450) for dim in (potentialCols[i], potentialCols[j]): hists = None for point in point_collect: hist = histogram(point, dimension=dim) if hists is None: hists = hist else: hists *= hist body += hists body = body.opts( opts.Scatter(alpha=0.9), opts.Histogram(alpha=0.9, height=450), opts.Layout(shared_axes=True, shared_datasource=True)).cols(3) renderer.save(body, os.path.join(self.directory, cachebust+"combined_gating"))
def makeHoverScatter(combineddf1, columns, labels, xlims, ylims): """ makes a 3 plot scatter layout labels is 3 x nlabels array where first two are x and y others are tooltips same with columns e.g. ['Amp1','CT1','Category','Sample'] all x and y values are set to min 0 """ hv.extension('bokeh', width=90) def setDFColLim(df, column, lim): lowind = np.where(df[column] < lim) tempvals = df[column].values tempvals[lowind] = lim df[column] = tempvals combineddf = combineddf1.copy() combineddf.replace(float('NaN'), 0.0, inplace=True) for i in range(3): for j in range(2): setDFColLim(combineddf, columns[i][j], 0.0) tooltips1 = [(labels[0][i] + ':', '@' + columns[0][i]) for i in range(len(labels[0]))] hover1 = HoverTool(tooltips=tooltips1) tooltips2 = [(labels[1][i] + ':', '@' + columns[1][i]) for i in range(len(labels[1]))] hover2 = HoverTool(tooltips=tooltips2) tooltips3 = [(labels[2][i] + ':', '@' + columns[2][i]) for i in range(len(labels[2]))] hover3 = HoverTool(tooltips=tooltips3) scat1 = hv.Scatter(combineddf, columns[0][0], vdims=columns[0][1:]).opts(tools=[hover1], size=8, alpha=0.5, width=300, title=targets[0], ylim=ylims, xlim=xlims) scat2 = hv.Scatter(combineddf, columns[1][0], vdims=columns[1][1:]).opts(tools=[hover2], size=8, alpha=0.5, width=300, title=targets[1], ylim=ylims, xlim=xlims) scat3 = hv.Scatter(combineddf, columns[2][0], vdims=columns[2][1:]).opts(tools=[hover3], size=8, alpha=0.5, width=300, title=targets[2], ylim=ylims, xlim=xlims) layout = scat1 + scat2 + scat3 return layout
def second_order(days_window): data_imputed = data data_imputed.Volume = data_imputed.Volume.interpolate() return hv.Scatter(pd.concat([data_imputed.Date, data_imputed.Volume.rolling(days_window).mean()], names=['Date', 'Volumne Trend'], axis=1) .dropna()).redim(Volume='Mean Trend') + \ hv.Scatter(pd.concat([data_imputed.Date, data_imputed.Volume.rolling(days_window).cov()], names=['Date', 'Volumne Variance'], axis=1) .dropna()).redim(Volume='Volume Variance').options(color='#FF7E47')
def plot_bearing(self) -> hv.Overlay: """ Makes a time plot of all the data in this file. """ df = self.df c1 = hv.Curve((df.time, df.signal), 'Time', self.name, label='Scaled Signal') c1 *= hv.Scatter(c1) c2 = hv.Curve((df.time, df.bearing), 'Time', self.name, label='Bearing') c2 *= hv.Scatter(c2) return c1 * c2
def plot(self): import holoviews as hv if not self.data: return hv.Scatter([]) * hv.Path([]) if not self.vdim > 1: return hv.Scatter(self.data) * hv.Path([]) else: xs = list(self.data.keys()) ys = list(self.data.values()) return hv.Path((xs, ys)) * hv.Scatter([])
def plot_dataset_2d(X_train, y_train, X_test, y_test): idx = y_train == 0 idx_test = y_test == 0 clase_0_train = hv.Scatter({ "x": X_train[idx, 0], "y": X_train[idx, 1] }, label="Clase 0 train").opts(color="b", size=20, alpha=0.5, tools=["hover"]) clase_1_train = hv.Scatter({ "x": X_train[~idx, 0], "y": X_train[~idx, 1] }, label="Clase 1 train").opts(color="r", size=20, alpha=0.5, tools=["hover"]) clase_0_test = hv.Scatter( { "x": X_test[idx_test, 0], "y": X_test[idx_test, 1] }, label="Clase 0 test").opts(color="b", size=20, alpha=0.5, marker="s", tools=["hover"]) clase_1_test = hv.Scatter( { "x": X_test[~idx_test, 0], "y": X_test[~idx_test, 1] }, label="Clase 1 test").opts(color="r", size=20, alpha=0.5, marker="s", tools=["hover"]) plot = clase_0_train * clase_1_train * clase_0_test * clase_1_test plot = plot.opts( width=550, height=450, title="Dataset de ejemplo", xlabel="Feature 1", ylabel="Feature 2", legend_position="top", xlim=(7.5, 12.3), ylim=(-1.5, 6), ) return plot
def show( self, data, # pylint: disable=too-many-arguments,too-many-locals keys=(), beads=(), trackorder='trackorder', align=True, ref=None, **kwa) -> hv.DynamicMap: "return a dynamic map" def _fcn(key, bead): info = data if isinstance(data, pd.DataFrame) else data[key] return self.showone(info[info.bead == bead], ref, trackorder=trackorder, align=align, **kwa) if isinstance(data, pd.DataFrame): _f1 = lambda x: _fcn(None, x) if len(beads) == 0: beads = sorted(data.bead.unique()) out = (hv.DynamicMap(_f1, kdims=['bead' ]).redim.values(bead=list(beads))) elif len(keys) == 1: _f2 = lambda x: _fcn(keys[0], x) out = (hv.DynamicMap(_f2, kdims=['bead' ]).redim.values(bead=list(beads))) elif len(beads) == 1: _f3 = lambda x: _fcn(x, beads[0]) out = (hv.DynamicMap(_f3, kdims=['data']).redim.values(data=list(keys))) else: out = (hv.DynamicMap(_fcn, kdims=['data', 'bead' ]).redim.values(data=list(keys), bead=list(beads))) if self.hpin: # type: ignore pos = self.hpin.pos # type: ignore tracks = list(pos.track.unique()) rpos = pos[pos.track == getreference(tracks)].position.values out = (out * hv.Scatter(pos[pos.target & pos.strand], 'track', 'position').options(color='green') * hv.Scatter(pos[pos.target & ~pos.strand], 'track', 'position').options(color='red') * hv.Scatter((np.repeat( tracks, rpos.size), np.concatenate( [rpos] * len(tracks)))).options(color='gray')) return out
def __plot_decision_boundaries(X, y, y_pred, resolution: int = 100, embedding=None): if embedding is None: embedding = TSNE(n_components=2, random_state=160290).fit_transform(X) x_min, x_max = safe_bounds(embedding[:, 0]) y_min, y_max = safe_bounds(embedding[:, 1]) xx, yy = np.meshgrid(np.linspace(x_min, x_max, resolution), np.linspace(y_min, y_max, resolution)) # approximate Voronoi tesselation on resolution x resolution grid using 1-NN background_model = KNeighborsClassifier(n_neighbors=1).fit( embedding, y_pred) voronoi_bg = background_model.predict(np.c_[xx.ravel(), yy.ravel()]) voronoi_bg = voronoi_bg.reshape((resolution, resolution)) mesh = hv.QuadMesh((xx, yy, voronoi_bg)).opts(cmap="viridis") points = hv.Scatter( { "x": embedding[:, 0], "y": embedding[:, 1], "pred": y_pred, "class": y }, kdims=["x", "y"], vdims=["pred", "class"], ) errors = y_pred != y failed_points = hv.Scatter( { "x": embedding[errors, 0], "y": embedding[errors, 1] }, kdims=["x", "y"]).opts(color="red", size=5, alpha=0.9) points = points.opts(color="pred", cmap="viridis", line_color="grey", size=10, alpha=0.8, tools=["hover"]) plot = mesh * points * failed_points plot = plot.opts(xaxis=None, yaxis=None, width=500, height=450, title="Decision boundaries on TSNE") return plot
def plot_position(time, pos, color='royalblue', fig_size=400, frame_width=800, aspect=3): if hv.Store.current_backend == 'bokeh': return hv.Scatter((time, pos)).opts(color=color, frame_width=frame_width, aspect=aspect) elif hv.Store.current_backend == 'matplotlib': return hv.Scatter((time, pos)).opts(color=color, fig_size=fig_size, aspect=aspect)
def _showfp(track): data = fpos[fpos.track == track] beads = data.bead.unique() dtl = cls.detailed(dico.config, data, precision=precision) disp = getattr(Detailed(dico, dtl), 'display')(zero=False).display() crv = hv.Curve((list(rng), [3, 3])).options(linewidth=20, alpha=.5) ovr = hv.Overlay(list(disp) + [crv]) if scatter: scatt = (hv.Scatter(data, 'bead', 'z').options(jitter=.8) * hv.Scatter( (np.concatenate([beads] * 2), [rng[0]] * len(beads) + [rng[0]] * len(beads)))) return (ovr + scatt).cols(1) return ovr
def showone( self, # pylint: disable=too-many-arguments,too-many-locals data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs): "display the data" if not isinstance(data, pd.DataFrame): data = self.peaks(data) if align: data = self.alignbead(data, ref=ref) # type: ignore ref = None data = data.sort_values(['bead', trackorder, 'peakposition', 'avg']) assert 'resolution' in data.columns if ref is None: ref = 'identity' if 'identity' in data.columns else 'track' cols = ['resolution', 'hybridisationrate', 'averageduration'] dim = hv.Dimension("z", label="base pairs") args = ref, ['avg'] + cols[1:] opts = dict(jitter=.75, alpha=.2) if 'reference' in data: isna = data.reference.isna() out = ( hv.Scatter(data[~isna], *args, label='events').options(**opts).redim(avg=dim) * hv.Scatter(data[isna], *args, label='unknown events').options( **opts).redim(avg=dim)) else: out = (hv.Scatter(data, *args, label='events').options(**opts).redim(avg=dim)) out *= (hv.Scatter(data, ref, ['peakposition'] + cols[:1], label='peaks').options( size_index='resolution', scaling_factor=scaling_factor, alpha=.01, line_alpha=.1).redim(peakposition=dim)) args = dict(style=dict(color='gray', alpha=.5, size=5), group='ref') for i, j in seqs.items(): out = self.showhpin(data, j, ref, label=i, **args) * out return out if self.hpalign else out
def two_ecdf(data1, data2): '''Returns a scatter plot of two ECDFs overlayed''' scatter1 = hv.Scatter(data=utils.ecdf_vals(data1), kdims=['time to catastrophe (s)'], vdims=['ECDF'], label='labeled') scatter2 = hv.Scatter(data=utils.ecdf_vals(data2), kdims=['time to catastrophe (s)'], vdims=['ECDF'], label='not labeled') chart = (scatter1 * scatter2).opts(legend_position='bottom_right') return chart
def plot_and_save_cache_access_time_graph(df, filename): scatter = hv.Scatter( (df.index + 2, df["access"])).opts(xticks=[2, 4, 6, 8, 10, 12, 14, 16], xlabel="memory size: 2x [KB]", ylabel="access time [ns/count]") scatter_log = hv.Scatter( (df.index + 2, df["access"])).opts(logy=True, xticks=[2, 4, 6, 8, 10, 12, 14, 16], xlabel="memory size: 2x [KB]", ylabel="log access time [ns/count]") access = scatter + scatter_log renderer = hv.renderer('matplotlib') renderer.save(access, 'cache_access_time')
def build_basemap(nc_list): ds_platform = xr.open_mfdataset(nc_list, group='Platform', concat_dim='location_time', combine='by_coords').to_dataframe() pathing_plot = hv.Scatter(ds_platform, vdims='longitude', kdims='latitude') return pathing_plot
def plot_and_save_process_graph(holoviews_table, filename): '''plot and save process graph from output file made by loop.py ''' process = hv.Scatter(holoviews_table, 'ms', 'process') renderer = hv.renderer('matplotlib') renderer.save(process, 'process_' + filename)
def dimensionality_reduction( sample: pd.Series, background_df: pd.DataFrame, genes: List[str], col: str, method='trimap') -> Tuple[pd.DataFrame, hv.Scatter]: """ Wrapper for returning trimap plot with column for `color_index` and `size_index` Args: sample: n-of-1 sample. Gets own label background_df: Background dataset genes: Genes to use in dimensionality reduction col: Column to use for color_index method: Method of dimensionality reduction. `trimap` or `tsne` Returns: Holoviews Scatter object of plot with associated vdims """ assert method == 'trimap' or method == 'tsne', '`method` must be either `trimap` or `tsne`' combined = background_df.append(sample) if method == 'trimap': reduced = trimap.TRIMAP().fit_transform(combined[genes]) else: reduced = t_sne.TSNE().fit_transform(combined[genes]) df = pd.DataFrame(reduced, columns=['x', 'y']) df[col] = background_df[col].tolist() + [f'N-of-1 - {sample[col]}'] df['size'] = [1 for _ in background_df[col]] + [5] return df, hv.Scatter(data=df, kdims=['x'], vdims=['y', col, 'size'])
def plot_phase_diagrams(filenames,fileout): for i in range(len(filenames)): print 'i: ',i ds = yt.load(filenames[i]) center_guess = initial_center_guess(ds,track_name) halo_center = get_halo_center(ds,center_guess) rb = sym_refine_box(ds,halo_center) args = filenames[i].split('/') sim_label = args[-3] dens = np.log10(rb['H_nuclei_density']) temp = np.log10(rb['Temperature']) df = pd.DataFrame({'temp':temp, 'dens':dens}) phase_scatter = hv.Scatter(df,kdims=['dens'],vdims=['temp'],label=sim_label) #phase_data = np.zeros((len(rb['H_nuclei_density']),2)) #phase_data[:,0] = np.log10(rb['H_nuclei_density']) #phase_data[:,1] = np.log10(rb['Temperature']) #points = hv.Points(phase_data,kdims=['nH','temp'],label=sim_label) hv.opts({'Histogram': {'style': {'alpha':0.3, 'fill_color':'k'}}}) xhist = (histogram(phase_scatter, bin_range=(-7.5, 1), dimension='dens',normed=True)) #,alpha=0.3, fill_color='k')) yhist = (histogram(phase_scatter, bin_range=(3, 8.5), dimension='temp',normed=True)) #,alpha=0.3, fill_color='k')) if i == 0: phase_plot = (datashade(phase_scatter,cmap=cm.plasma, dynamic=False,x_range=(-7.5,1),y_range=(3,8.5))) << yhist(plot=dict(width=125)) << xhist(plot=dict(height=125)) else: plot2 = (datashade(phase_scatter,cmap=cm.plasma, dynamic=False,x_range=(-7.5,1),y_range=(3,8.5))) << yhist(plot=dict(width=125)) << xhist(plot=dict(height=125)) phase_plot = phase_plot + plot2 renderer = hv.renderer('bokeh').instance(fig='html') renderer.save(phase_plot, fileout) return
def plot_mean_age(years, mean_ages): ''' Function to plot mean age data given a list of mean_ages and list of years :param: mean_ages :type: list :param: years :type: list :returns: holoviews plot ''' assert isinstance(mean_ages, list) assert isinstance(years, list) assert len(years) > 0 assert len(mean_ages) > 0 assert all(i >= 0 for i in mean_ages) assert all(i >= 0 for i in years) assert all(isinstance(i, float) for i in mean_ages) assert all(isinstance(i, int) for i in years) # mean ages y = mean_ages # years x = years # create tuples d = list(zip(x, y)) # Draw a scatter plot s = hv.Scatter(d, hv.Dimension('Year'), 'Mean age').opts(size=8, tools=['hover'], title='Mean age of diabetics in US') # Draw a line c = hv.Curve(d, hv.Dimension('Year'), 'Mean age') # Overlay both and return return s * c
def scatter( self, x, y, colorby=None, options={}, styles={}, title="Scatter Plot", force=False, ): """Possible options: width, height, legend_position [e.g. "top_right"] Possible styles: size, cmap [brg, Accent, rainbow, jet, flag, Wistia] Only works when the data object is a Pandas DataFrame.""" if not HOLOVIEWS: print("* HoloViews not available.") return None hover = struct_hover(self, force=force) plot_options = { "width": 800, "height": 450, "legend_position": "top_left", "tools": [hover], } plot_styles = {"size": 8, "cmap": "brg"} plot_options.update(options) plot_styles.update(styles) vdims = [y, self.id_col, "Image"] if colorby is not None: vdims.append(colorby) plot_options["color_index"] = len(vdims) opts = {"Scatter": {"plot": plot_options, "style": plot_styles}} scatter_plot = hv.Scatter(self.data, x, vdims=vdims, label=title) return scatter_plot(opts)
def gen_plot_scat(df, xRange=None, yRange=None, nomSize=None): """ Return holoviews plot Parameters ---------- df: pandas.DataFrame DataFrame containing data to be plotted """ # Get bounds for graph colNames = list(df) if xRange == None or xRange[0] == 'auto': lowX = df[colNames[0]].quantile(0.01) highX = df[colNames[0]].quantile(0.99) else: lowX = xRange[0] highX = xRange[1] if yRange == None or yRange[0] == 'auto': lowY = df[colNames[1]].quantile(0.01) highY = df[colNames[1]].quantile(0.99) else: lowY = yRange[0] highY = yRange[1] lastTime = df[colNames[0]].last_valid_index() dateStr = time.strftime("%b %d %Y %H:%M:%S", time.localtime(lastTime)) if df.shape[0] > 0: scatterSize = max(1, 10 - int(np.log(df.shape[0]) / 2.)) print(scatterSize, int(np.log(df.shape[0]) / 2.), np.log(df.shape[0])) else: scatterSize = 10. return hv.Scatter( df, group="Number of events: %d at %s" % (len(df.index), dateStr) ).redim.range(**{ df.columns[0]: (lowX, highX), df.columns[1]: (lowY, highY) }).opts( norm=dict(framewise=True) ).options( size=scatterSize, fontsize={ 'ticks': int(nomSize * 1.2), 'title': int(nomSize * 2), 'labels': int(nomSize * 1.), 'xlabel': int(nomSize * 1.5), 'ylabel': int(nomSize * 1.5) } ) # (not supported yet as far as I can tell - maybe in newer version, fontstyle={'ticks':'bold'}
def true_cdf_plot(beta_1, beta_2, n_points=150000): #Generate num points x_dimension = np.linspace(0, 1500, num=n_points) #Generate list of tuples with t and F(t) of the distribution cdf = [ ( t, (beta_1 * beta_2 / (beta_2 - beta_1)) * ( (1 / beta_1) * (1 - np.exp(-beta_1 * t)) - (1 / beta_2) * (1 - np.exp(-beta_2 * t)) ), ) for t in x_dimension ] #Plot the above cdf as a scatter plot using holoviews true_cdf = hv.Scatter( cdf, "Time to catastrophe (t)", "CDF", label="TTC CDF" ).opts( width=400, padding=0.1, xlim=(0, 1500), color=bebi103.hv.default_categorical_cmap[1], ) #Generate plot of approximated ecdf (see function create_approx_ecdf() above) approx_cdf = create_poisson_ecdf(beta_1, beta_2, non_dim=False).opts( color=bebi103.hv.default_categorical_cmap[0] ) #Return an overlay of both plots return (true_cdf * approx_cdf).opts( legend_offset=(10, 20), legend_position="bottom_right" )
def test_holoviews_pane_mpl_renderer(document, comm): curve = hv.Curve([1, 2, 3]) pane = Pane(curve) # Create pane row = pane._get_root(document, comm=comm) assert isinstance(row, BkRow) assert len(row.children) == 1 assert len(pane._callbacks) == 1 model = row.children[0] assert pane._models[row.ref['id']] is model div = get_div(model) assert '<img' in div.text # Replace Pane.object scatter = hv.Scatter([1, 2, 3]) pane.object = scatter model = row.children[0] div2 = get_div(model) assert div2.text != div.text # Cleanup pane._cleanup(row) assert pane._callbacks == {} assert pane._models == {}
def _get_linked_plots(backend: str = "plotly") -> Tuple: """Returns a tuple (scatter, hist) of linked plots Args: backend (str, optional): "plotly" or "bokeh". Defaults to "plotly". Returns: [Tuple]: Returns a tuple (scatter, hist) of linked plots """ dataset = hv.Dataset(IRIS_DATASET) scatter = hv.Scatter(dataset, kdims=["sepal_length"], vdims=["sepal_width"]) hist = hv.operation.histogram(dataset, dimension="petal_width", normed=False) # pylint: disable=no-value-for-parameter selection_linker = hv.selection.link_selections.instance() scatter = selection_linker(scatter).opts( opts.Scatter(**OPTS["all"]["scatter"], **OPTS[backend]["scatter"])) hist = selection_linker(hist).opts( opts.Histogram(**OPTS["all"]["hist"], **OPTS[backend]["hist"])) return scatter, hist
def time_hover_gen(self, data, vdims, x_range): lidx = 0 ridx = len(self.time_df) if x_range is not None: lidx = int(x_range[0]) ridx = int(x_range[1]) num_pts = ridx - lidx + 1 size = 1 if num_pts > 500: size = .5 if num_pts > 1000: size = .25 if num_pts > 2000: size = .125 hover = HoverTool(tooltips=[('Sample', '@{Sample}'), (vdims, '@{}'.format(vdims))], mode='vline') scatt = hv.Scatter(self.time_df[lidx:ridx], kdims='Sample', vdims=vdims, group='Time Domain').opts(size=size, tools=[hover]) return scatt
def test_holoviews_pane_bokeh_renderer(document, comm): curve = hv.Curve([1, 2, 3]) pane = Pane(curve) # Create pane row = pane.get_root(document, comm=comm) assert isinstance(row, BkRow) assert len(row.children) == 1 model = row.children[0] assert isinstance(model, Figure) assert pane._models[row.ref['id']][0] is model renderers = [r for r in model.renderers if isinstance(r, GlyphRenderer)] assert len(renderers) == 1 assert isinstance(renderers[0].glyph, Line) # Replace Pane.object scatter = hv.Scatter([1, 2, 3]) pane.object = scatter model = row.children[0] assert isinstance(model, Figure) renderers = [r for r in model.renderers if isinstance(r, GlyphRenderer)] assert len(renderers) == 1 assert isinstance(renderers[0].glyph, Scatter) assert pane._models[row.ref['id']][0] is model # Cleanup pane._cleanup(row) assert pane._models == {}
def visits_plot_per_metric(df, x, y, hover_columns=None, filt=0): """ * x: name of the column for x-axis * y: name of the column for y-axis * hover_columns: list of column names for hover information """ from bokeh.models import HoverTool from holoviews.core.util import dimension_sanitizer if hover_columns: _tt = [(n, "@{%s}" % dimension_sanitizer(n)) for n in hover_columns] hover = HoverTool(tooltips=_tt) else: hover = "hover" # 'x' must be renamed for Hv/Pn link axes with equal name/label; # in here, it will cause plots on different filter to have their # x-axis values merged (producing big blank areas in each plot) x_renamed = "visits ({filt})".format(filt=filt) df = df.sort_values(x) df[x_renamed] = df[x].astype(str) curve = hv.Curve(df, x_renamed, y) points = hv.Scatter(df, [x_renamed, y], hover_columns).opts(size=8, line_color="white", tools=[hover, "tap"], toolbar="above") return (curve * points).redim(y=hv.Dimension(y, range=(-1, 1)))