def concatenated_summary_curve_factory( cdf, kdims="Cycle_Index", vdims="Charge_Capacity(mAh/g)", title="Summary Curves", fill_alpha=0.8, size=12, width=800, legend_position="right", colors=None, markers=None, ): # TODO: missing doc-string if not hv_available: print("This function uses holoviews. But could not import it." "So I am aborting...") return if colors is None: colors = hv.Cycle("Category10") if markers is None: markers = hv.Cycle(["circle", "square", "triangle", "diamond"]) groups = [] curves_opts = [] curves = {} for indx, new_df in cdf.groupby(level=0, axis=1): g = indx.split("_")[1] groups.append(g) n = hv.Scatter(data=new_df[indx], kdims=kdims, vdims=vdims, group=g, label=indx).opts(fill_alpha=fill_alpha, size=size) curves[indx] = n ugroups = set(groups) max_sub_group = max([groups.count(x) for x in ugroups]) markers = markers[max_sub_group] colors = colors[len(ugroups)] for g, c in zip(ugroups, colors.values): curves_opts.append(opts.Scatter(g, color=c, marker=markers)) curves_overlay = hv.NdOverlay(curves, kdims="cell id").opts( opts.NdOverlay(width=800, legend_position=legend_position, title=title), *curves_opts, ) return curves_overlay
def update_fn(): if self.sweep2D: dispsq = hv.Image((x_data, y_data, self.point_dict[self.measInst[0].name]), kdims=[self.inst1.name, self.inst2.name], vdims=self.measInst[0].name).opts(norm=dict(framewise=True), plot=dict(colorbar=True), style=dict(cmap='jet')) for i in range(1,len(self.measInst)): dispsq += hv.Image((x_data, y_data, self.point_dict[self.measInst[i].name]), kdims=[self.inst1.name, self.inst2.name], vdims=self.measInst[i].name).opts(norm=dict(framewise=True), plot=dict(colorbar=True), style=dict(cmap='jet')) else: dispsq = hv.Curve((x_data, self.point_dict[self.measInst[0].name]), kdims=self.inst1.name, vdims=self.measInst[0].name).options(framewise=True, color=hv.Cycle('Colorblind').values[0]) for i in range(1, len(self.measInst)): dispsq += hv.Curve((x_data, self.point_dict[self.measInst[i].name]), kdims=self.inst1.name, vdims=self.measInst[i].name).options(framewise=True, color=hv.Cycle('Colorblind').values[i]) return dispsq
def to_ndoverlay(self, colors=None, labels=None): """ Fetches the vector tile (from python cache or from the local disk or from the web service <- search order) and returns a NdOverlay of Shape Elements with a numeric index kwargs: - colors (iterable of color values, or str indicating a colormap definted in holoviews) : Used to generate a itertools.cycle to cycle through color values. : Default is 'Category20' eg: color=bokeh.palettes.Category20_10 For hv.Cycle('colomap_name')'s usage, refer to: http://holoviews.org/user_guide/Style_Mapping.html """ gdf = self.to_gdf() colors = colors or 'Category20' # return ndoverlay of each shape ndoverlay = hv.NdOverlay({ i: gv.Shape(geom).opts(fill_color=hv.Cycle(colors)) for (i, geom) in enumerate(gdf.geometry) }) # if labels is not None: # ndoverlay = relabel_children(ndoverlay, labels) return ndoverlay
def plot_heatmap(self): ##Stacked Bar chart for Day and Event Type self.day_hour = self.data.groupby(by=['Weekday', 'Hour']).agg({ 'Weekday': 'count' }).rename(columns={'Weekday': 'Sessions'}) self.day_hour = self.day_hour.reset_index() #print(self.day_hour) key_dimensions_hm = [('Weekday', 'Weekday'), ('Hour', 'Hour')] value_dimensions_hm = [('Sessions')] macro_hm = hv.Table(self.day_hour, key_dimensions_hm, value_dimensions_hm) hm = macro_hm.to.heatmap(['Weekday', 'Hour'], 'Sessions', []).options(width=748, show_legend=True, height=525, color=hv.Cycle('Spectral'), tools=['hover'], title_format="Heatmap") hm_plot = renderer.get_plot(hm).state hm_plot.y_range = FactorRange(factors=[ '01 AM', '02 AM', '03 AM', '04 AM', '05 AM', '06 AM', '07 AM', '08 AM', '09 AM', '10 AM', '11 AM', '12 PM', '01 PM', '02 PM', '03 PM', '04 PM', '05 PM', '06 PM', '07 PM', '08 PM', '09 PM', '10 PM', '11 PM' ]) hm_plot.x_range = FactorRange( factors=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']) return hm_plot
def plot_1d_min_max_with_region_bar( run_diags: RunDiagnostics, varfilter_min: str, varfilter_max: str, ) -> HVPlot: """Plot all diagnostics whose name includes varfilter. Plot is overlaid across runs. All matching diagnostics must be 1D.""" p = hv.Cycle("Colorblind") hmap = hv.HoloMap(kdims=["variable", "region", "run"]) variables_to_plot = run_diags.matching_variables(varfilter_min) for run in run_diags.runs: for min_var in variables_to_plot: max_var = min_var.replace(varfilter_min, varfilter_max) vmin = run_diags.get_variable(run, min_var).rename("min") vmax = run_diags.get_variable(run, max_var).rename("max") style = "solid" if run_diags.is_baseline(run) else "dashed" long_name = vmin.long_name region = min_var.split("_")[-1] # Area plot doesn't automatically add correct y label ylabel = f'{vmin.attrs["long_name"]} {vmin.attrs["units"]}' hmap[(long_name, region, run)] = hv.Area( (vmin.time, vmin, vmax), label="Min/max", vdims=["y", "y2"]).options(line_dash=style, color=p, alpha=0.6, ylabel=ylabel) return HVPlot(_set_opts_and_overlay(hmap))
def create_line(ds, fold, show_unselected): unique_folds = ds.data.data_split.unique() hover = HoverTool(tooltips=[("fold", "@data_split")]) available_colors = my_fold_colors(ds) alpha = .05 if show_unselected else 0 cmap = [ color if this_fold == fold else hex_to_rgb(color, alpha=alpha) for this_fold, color in zip(unique_folds, available_colors) ] lines = (ds.sort().to(hv.Curve, kdims=['x'], vdims=['y_pred'], groupby=['data_split']).overlay(['data_split']).opts( 'Curve', color=hv.Cycle(cmap), line_width=5, tools=[hover]).opts(show_legend=False, width=800, height=550, xlim=(0, 11), ylim=(0, 13))) return lines
def my_fold_colors(ds): available_colors = hv.Cycle(colorcet.glasbey).values while len(available_colors) < len(ds.data.data_split.unique()): available_colors = available_colors + available_colors return available_colors
def fetch_mpl_obj(self): group = "Gas Concentration vs Time" plot = dict(aspect=2) legend = dict(legend_position='best', aspect=2) graph = None options = hv.Store.options(backend='matplotlib') options.Curve = hv.Options('style', color=hv.Cycle(values=self.gases.values()), linewidth=2) for data in self.graph_data: graph_inter = hv.Curve(data['data'], vdims=['Gas Concentration'], kdims=['Time'], label=data['label'], group=group) if graph: graph *= graph_inter else: graph = graph_inter for data in self.text_labels: graph *= hv.Text(data['key'], data['value'], data['date'], fontsize=10) opts = {'Curve': {'plot': plot}, 'Overlay': {'plot': legend}} self.mpl_obj = graph(opts) if graph else None
def set_cycle(fig, name, xs, typs, extra=None): return set_option( fig=fig, name=name, val=hv.Cycle(xs), typs=typs, extra=extra, )
def get_cc(): from string import ascii_lowercase import holoviews cc = type( 'color', (), dict( zip(ascii_lowercase, holoviews.Cycle().default_cycles['default_colors']))) return cc
def add_color(solutions, colormap='Category20'): categories = set(solutions['line_text'].unique()) color_dict = { category: color for category, color in zip(categories, itertools.cycle(hv.Cycle(colormap).values)) } solutions['color'] = solutions['line_text'].map(lambda k: color_dict[k]) return solutions
def __init__(self): from string import ascii_lowercase import holoviews as hv self.names, self.codes = zip( *(zip(ascii_lowercase, hv.Cycle().default_cycles['default_colors']))) for name, code in zip(self.names, self.codes): setattr(self, name, code) self.reset()
def view_network(self): if self.mapdf is None: return pn.indicators.LoadingSpinner(value=True, width=100, height=100) G = get_graph(self.model_path) if G.order == 0: return pn.pane.Alert( f'## No network file found on {self.model_path}') nodeloc = list( filter(lambda n: n[1]['name'] == self.localities, G.nodes(data=True))) # print(nodeloc, self.localities) if nodeloc == []: return pn.pane.Alert(f'## Please select a locality.') H = get_subgraph(G, nodeloc[0][0]) partial_map = self.mapdf[self.mapdf.geocode.isin(H.nodes)] partial_map = partial_map.set_crs(4326) partial_map = partial_map.to_crs(3857) # Converting to web mercator centroids = [(c.x, c.y) for c in partial_map.centroid] # Draw the graph using Altair gcs = [int(gc) for gc in partial_map.geocode] pos = dict(zip(gcs, centroids)) # viz = nxa.draw_networkx( # G, pos=pos, # node_color='weight', # cmap='viridis', # width='weight', # edge_color='black', # ) kwargs = dict(width=800, height=800, xaxis=None, yaxis=None) hv.opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs)) colors = ['#000000'] + hv.Cycle('Category20').values epi_graph = hv.Graph.from_networkx(H, positions=pos) epi_graph.opts(cmap=colors, node_size=10, edge_line_width=1, directed=True, node_line_color='gray', edge_color='gray', node_color='circle') tiles = gv.tile_sources.Wikipedia f = bundle_graph(epi_graph) * tiles source = epi_graph.nodes.clone() # print(epi_graph.nodes.data.iloc[0]) source.data = epi_graph.nodes.data[epi_graph.nodes.data.name == self.localities] return f * source.opts(color='red')
def get_single_legend(layout, kdim_opts, kdim): """ Create the portion of a legend pertaining to a single kdim. """ other_kdims = [kd.name for kd in layout.kdims if kd.name!=kdim] l = deepcopy(layout).drop_dimension(other_kdims) return l.opts( getattr(opts, type(l).name)(xaxis=None, yaxis=None, legend_position='top_left', show_frame=False, **hw), getattr(opts, l.type.name)(**{**other_kdim_defaults, **{k: hv.Cycle(v) for k, v in kdim_opts[kdim].items()}}), ).map(lambda x: x.iloc[:0], l.type)
def faceted_legend_opts(kdim_opts): """ Cycle across all combinations of styling options and return the holoviews `opts` object. TO DO: exclude variations that don't exist in the data License ------- GNU-GPLv3, (C) A. R. (https://github.com/poplarShift/python-data-science-utils) """ options = (list(l) for l in zip(*product(*(list(x.values())[0] for x in kdim_opts.values())))) options = {list(k.keys())[0]: hv.Cycle(v) for k, v in zip(kdim_opts.values(), options)} return options
def plot_1d(run_diags: RunDiagnostics, varfilter: str) -> HVPlot: """Plot all diagnostics whose name includes varfilter. Plot is overlaid across runs. All matching diagnostics must be 1D.""" p = hv.Cycle("Colorblind") hmap = hv.HoloMap(kdims=["variable", "run"]) vars_to_plot = run_diags.matching_variables(varfilter) for run in run_diags.runs: for varname in vars_to_plot: v = run_diags.get_variable(run, varname).rename("value") style = "solid" if run_diags.is_baseline(run) else "dashed" long_name = v.long_name hmap[(long_name, run)] = hv.Curve(v, label=varfilter).options(line_dash=style, color=p) return HVPlot(_set_opts_and_overlay(hmap))
def event_selection(self): if not self.selection_spaces: return hv.Points(dset, ["cs1", "cs2"]).opts(color="blue") colors = hv.Cycle('Category10').values plots = [ hv.Points(dset, dims).opts(color=c) for c, dims in zip(colors, self.selection_spaces) ] layout = hv.Layout(plots).cols(6) lsp = hv.selection.link_selections.instance() self.linked_selection = lsp layout = self.linked_selection(layout) return layout
def scatter_matrix(data, c=None, chart='scatter', diagonal='hist', alpha=0.5, **kwds): """ Scatter matrix of numeric columns. Parameters: ----------- data: DataFrame c: str, optional Column to color by chart: str, optional Chart type (one of 'scatter', 'bivariate', 'hexbin') diagonal: str, optional Chart type for the diagonal (one of 'hist', 'kde') kwds: hvplot.scatter options, optional Returns: -------- obj : HoloViews object The HoloViews representation of the plot. """ data = _hv.Dataset(data) supported = list(HoloViewsConverter._kind_mapping) if diagonal not in supported: raise ValueError('diagonal type must be one of: %s, found %s' % (supported, diagonal)) if chart not in supported: raise ValueError('Chart type must be one of: %s, found %s' % (supported, chart)) diagonal = HoloViewsConverter._kind_mapping[diagonal] chart = HoloViewsConverter._kind_mapping[chart] colors = _hv.plotting.util.process_cmap('Category10', categorical=True) chart_opts = dict(alpha=alpha, cmap=colors, tools=['box_select', 'lasso_select'], nonselection_alpha=0.1, **kwds) grid = _hv.operation.gridmatrix(data, diagonal_type=diagonal, chart_type=chart) if c: chart_opts['color_index'] = c grid = grid.map(lambda x: x.clone(vdims=x.vdims+[c]), 'Scatter') groups = _hv.operation.gridmatrix(data.groupby(c).overlay(), chart_type=chart, diagonal_type=diagonal) grid = (grid * groups).map(lambda x: x.get(0) if isinstance(x.get(0), chart) else x.get(1), _hv.Overlay) diagonal_opts = {'fill_color': _hv.Cycle(values=colors)} return grid.options({chart.__name__: chart_opts, diagonal.__name__: diagonal_opts})
def scatter(data, x, y, hue=None): key_dimensions = [(xi, xi) for xi in [x, hue]] value_dimensions = [(y, y)] macro = hv.Table(data, key_dimensions, value_dimensions) scatter = macro.to.scatter(x, y).overlay(hue) scatter.opts( opts.Scatter(color=hv.Cycle('Category20'), line_color='k', size=10, show_grid=True, width=700, height=400), opts.NdOverlay(legend_position='left', show_frame=False)) return scatter
def diurnal_component_plot( run_diags: RunDiagnostics, run_attr_name="run", diurnal_component_name="diurn_component", ) -> HVPlot: p = hv.Cycle("Colorblind") hmap = hv.HoloMap(kdims=["run", "surface_type", "short_varname"]) variables_to_plot = run_diags.matching_variables(diurnal_component_name) for run in run_diags.runs: for varname in variables_to_plot: v = run_diags.get_variable(run, varname).rename("value") short_vname, surface_type = _parse_diurnal_component_fields( varname) hmap[(run, surface_type, short_vname)] = hv.Curve( v, label=diurnal_component_name).options(color=p) return HVPlot(_set_opts_and_overlay(hmap, overlay="short_varname"))
def plot_1d_with_region_bar(run_diags: RunDiagnostics, varfilter: str) -> HVPlot: """Plot all diagnostics whose name includes varfilter. Plot is overlaid across runs. Region will be selectable through a drop-down bar. Region is assumed to be part of variable name after last underscore. All matching diagnostics must be 1D.""" p = hv.Cycle("Colorblind") hmap = hv.HoloMap(kdims=["variable", "region", "run"]) vars_to_plot = run_diags.matching_variables(varfilter) for run in run_diags.runs: for varname in vars_to_plot: v = run_diags.get_variable(run, varname).rename("value") style = "solid" if run_diags.is_baseline(run) else "dashed" long_name = v.long_name region = varname.split("_")[-1] hmap[(long_name, region, run)] = hv.Curve( v, label=varfilter, ).options(line_dash=style, color=p) return HVPlot(_set_opts_and_overlay(hmap))
def euler_table(x0, y0, n, h, func): """ Compute up to n euler steps with step size h for y' = f(x,y) starting from (x0,y0), returning the results in an hv.Table """ xl = [x0] yl = [y0] for i in range(n): x0, y0 = euler_step(x0, y0, h, func) xl.append(x0) yl.append(y0) if np.abs(x0) > 5. or np.abs(y0) > 5.: break # we ran off the grid return hv.Table(pd.DataFrame(dict(x=xl, y=yl)), kdims=['x'], vdims=['y']) line_colors = hv.Cycle(["Red", "Orange", "LightGreen", "Green"]) def euler_curve(x0, y0, n, h, func): """ Compute up to n euler steps with step size h for y' = f(x,y) starting from (x0,y0) return the results in an hv.Curve """ return euler_table(x0, y0, n, h, func).to.curve(label='h=%6.3f' % h).options(color=line_colors) def append_euler_plots(l, start, func, n=10000, h=[.5, .2, .01, .0011]): for hi in h: l.append(euler_curve(*start, n, hi, func))
def hatch_raise_view(self): # Load CSTK data # cstk_data = pd.read_csv('CSTK_DATA.csv', header=None).reset_index().head(100) # cstk_data.columns = ['CSTK Token Holders', 'CSTK Tokens'] # cstk_data['CSTK Tokens Capped'] = cstk_data['CSTK Tokens'].apply(lambda x: min(x, cstk_data['CSTK Tokens'].sum()/10)) self.cstk_data['Cap Raise'] = self.cstk_data['CSTK Tokens Capped'] * self.hatch_oracle_ratio # cap_plot = self.cstk_data.hvplot.area(title="Raise Targets Per Hatcher", x='CSTK Token Holders', y='Cap raise', yformatter='%.0f', label="Cap Raise", ylabel="XDAI Staked") self.cstk_data['Max Goal'] = self.max_raise # max_plot = self.cstk_data.hvplot.area(x='CSTK Token Holders', y='max_goal', yformatter='%.0f', label="Max Raise") self.cstk_data['Min Goal'] = self.min_raise # min_plot = self.cstk_data.hvplot.area(x='CSTK Token Holders', y='min_goal', yformatter='%.0f', label="Min Raise") self.cstk_data['Target Goal'] = self.target_raise # target_plot = self.cstk_data.hvplot.line(x='CSTK Token Holders', y='target_goal', yformatter='%.0f', label="Target Raise") bar_data = pd.DataFrame(self.cstk_data.iloc[:,3:].sum().sort_values(), columns=['Total']) bar_data['Hatch Tribute'] = bar_data['Total'] * self.hatch_tribute() bar_data['Funding Pool'] = bar_data['Total'] * (1-self.hatch_tribute()) # raise_bars = bar_data.hvplot.bar(yformatter='%.0f', title="Funding Pools", stacked=True, y=['Funding Pool', 'Hatch Tribute']).opts(color=hv.Cycle(['#0F2EEE', '#0b0a15', '#DEFB48'])) colors = ['#0F2EEE', '#0b0a15', '#DEFB48'] min_data = pd.Series(bar_data.T.iloc[1:]['Min Goal']) min_pchart = pie_chart(data=min_data, radius=0.2, title='Min Goal', colors=colors[:2]) target_data = pd.Series(bar_data.T.iloc[1:]['Target Goal']) target_pchart = pie_chart(data=target_data, radius=0.2, title='Target Goal', colors=colors[:2]) max_data = pd.Series(bar_data.T.iloc[1:]['Max Goal']) max_pchart = pie_chart(data=max_data, radius=0.2, title='Max Goal', colors=colors[:2]) funding_pool = pn.Column('### Funding Pool', pn.Row(min_pchart, target_pchart), max_pchart) stats = pd.DataFrame(self.cstk_data.iloc[:,3:].sum(), columns=['Total XDAI Staked']) stats['GMean XDAI Co-vested Per Hatcher'] = gmean(self.cstk_data.iloc[:,3:]) stats['XDAI Hatch Tribute'] = stats['Total XDAI Staked'] * self.hatch_tribute() stats['XDAI Funding Pool'] = stats['Total XDAI Staked'] * (1 - self.hatch_tribute()) stats['Total TECH Tokens'] = stats['Total XDAI Staked'] * self.hatch_exchange_rate self.total_target_tech_tokens = int(stats.loc['Target Goal']['Total TECH Tokens']) hatch_oracle_ratio_data = pd.DataFrame(data={'CSTK balance':[2000]}) hatch_oracle_ratio_data['Max wxDAI to be sent'] = self.hatch_oracle_ratio * hatch_oracle_ratio_data['CSTK balance'] hatch_oracle_ratio_bars = hatch_oracle_ratio_data.hvplot.bar(yformatter='%.0f', title="Hatch Oracle Ratio", stacked=False, y=['CSTK balance','Max wxDAI to be sent']).opts(color=hv.Cycle(colors), axiswise=True) #return pn.Column(cap_plot * max_plot * min_plot * target_plot, raise_bars, stats.sort_values('Total XDAI Staked',ascending=False).apply(round).reset_index().hvplot.table()) #return pn.Column(raise_bars, stats.sort_values('Total XDAI Staked',ascending=False).apply(round).reset_index().hvplot.table()) return pn.Column(hatch_oracle_ratio_bars, funding_pool)
def hatch_raise_view(self): # Load CSTK data # cstk_data = pd.read_csv('CSTK_DATA.csv', header=None).reset_index().head(100) # cstk_data.columns = ['CSTK Token Holders', 'CSTK Tokens'] # cstk_data['CSTK Tokens Capped'] = cstk_data['CSTK Tokens'].apply(lambda x: min(x, cstk_data['CSTK Tokens'].sum()/10)) self.cstk_data['Cap raise'] = self.cstk_data[ 'CSTK Tokens Capped'] * self.hatch_oracle_ratio cap_plot = self.cstk_data.hvplot.area( title="Raise Targets Per Hatcher", x='CSTK Token Holders', y='Cap raise', yformatter='%.0f', label="Cap Raise", ylabel="XDAI Staked") self.cstk_data[ 'max_goal'] = self.cstk_data['Cap raise'] * self.max_raise max_plot = self.cstk_data.hvplot.area(x='CSTK Token Holders', y='max_goal', yformatter='%.0f', label="Max Raise") self.cstk_data[ 'min_goal'] = self.cstk_data['Cap raise'] * self.min_raise min_plot = self.cstk_data.hvplot.area(x='CSTK Token Holders', y='min_goal', yformatter='%.0f', label="Min Raise") self.cstk_data[ 'target_goal'] = self.cstk_data['Cap raise'] * self.target_raise target_plot = self.cstk_data.hvplot.line(x='CSTK Token Holders', y='target_goal', yformatter='%.0f', label="Target Raise") bar_data = pd.DataFrame(self.cstk_data.iloc[:, 3:].sum().sort_values(), columns=['Total']) bar_data['Hatch Tribute'] = bar_data['Total'] * self.hatch_tribute bar_data['Funding Pool'] = bar_data['Total'] * (1 - self.hatch_tribute) raise_bars = bar_data.hvplot.bar( yformatter='%.0f', title="Funding Pools", stacked=True, y=['Funding Pool', 'Hatch Tribute' ]).opts(color=hv.Cycle(['#0F2EEE', '#0b0a15', '#DEFB48'])) stats = pd.DataFrame(self.cstk_data.iloc[:, 3:].sum(), columns=['Total XDAI Staked']) stats['GMean XDAI Co-vested Per Hatcher'] = gmean( self.cstk_data.iloc[:, 3:]) stats['XDAI Hatch Tribute'] = stats[ 'Total XDAI Staked'] * self.hatch_tribute stats['XDAI Funding Pool'] = stats['Total XDAI Staked'] * ( 1 - self.hatch_tribute) stats['Total TECH Tokens'] = stats[ 'Total XDAI Staked'] * self.hatch_exchange_rate self.total_target_tech_tokens = int( stats.loc['target_goal']['Total TECH Tokens']) return pn.Column( cap_plot * max_plot * min_plot * target_plot, raise_bars, stats.sort_values( 'Total XDAI Staked', ascending=False).apply(round).reset_index().hvplot.table())
def funding_pools(self): x = np.linspace(self.minimum_raise, self.maximum_raise) R = self.maximum_impact_hour_rate m = self.raise_horizon H = self.total_impact_hours y = [R * (x / (x + m * H)) for x in x] df = pd.DataFrame([x, y]).T df.columns = ['Total XDAI Raised', 'Impact Hour Rate'] # Minimum Results minimum_raise = self.minimum_raise minimum_rate = df[df['Total XDAI Raised'] > minimum_raise].iloc[0]['Impact Hour Rate'] minimum_cultural_tribute = self.total_impact_hours * minimum_rate # Expected Results expected_raise = self.total_impact_hours * self.raise_horizon try: expected_rate = df[df['Total XDAI Raised'] > expected_raise].iloc[0]['Impact Hour Rate'] except: expected_rate = df['Impact Hour Rate'].max() self.expected_impact_hour_rate = round(expected_rate, 5) expected_cultural_tribute = self.total_impact_hours * expected_rate # Target Results target_raise = self.target_raise try: target_rate = df[df['Total XDAI Raised'] > target_raise].iloc[0]['Impact Hour Rate'] except: target_rate = df['Impact Hour Rate'].max() self.target_impact_hour_rate = round(target_rate, 5) target_cultural_tribute = self.total_impact_hours * target_rate # Funding Pools and Tribute funding = pd.DataFrame.from_dict( { 'Mimimum': [ minimum_cultural_tribute, minimum_raise - minimum_cultural_tribute ], 'Expected': [ expected_cultural_tribute, expected_raise - expected_cultural_tribute ], 'Target': [ target_cultural_tribute, target_raise - target_cultural_tribute ] }, orient='index', columns=['Culture Tribute', 'Funding Pool']) funding_plot = funding.hvplot.bar( title="Expected and Target Funding Pools", stacked=True, ylim=(0, self.maximum_raise), yformatter='%.0f').opts( color=hv.Cycle(['#0F2EEE', '#0b0a15', '#DEFB48'])) return funding_plot
f1 + f2 + f3 + f4 + f5 + f6 #%% import holoviews as hv from holoviews import opts hv.extension('bokeh') from holoviews.operation import gridmatrix from bokeh.sampledata.iris import flowers from bokeh.palettes import brewer import bokeh.models as bmod counts = pd.read_csv(ippath) colors = brewer["Spectral"][len(counts.Genotype.unique()) + 1] colormap = { counts.Genotype.unique()[i]: colors[i] for i in range(len(counts.Genotype.unique())) } colors = [colormap[x] for x in counts.Genotype] print(colormap) iris_ds = hv.Dataset(counts).groupby('Genotype').overlay() point_grid = gridmatrix(iris_ds, chart_type=hv.Points) (point_grid).opts(opts.Bivariate(bandwidth=0.5, cmap=hv.Cycle(values=colors)), opts.Points(size=5, alpha=0.5), opts.NdOverlay(batched=False)) #%%
def set_defaults(): """ Set convenient HoloViews defaults Called without arguments, sets default visual plotting options for HoloViews. """ hv.opts.defaults( hv.opts.Bars( alpha=0.9, bar_width=0.6, cmap=default_categorical_cmap, color=default_categorical_cmap[0], frame_height=300, frame_width=400, hooks=[no_xgrid_hook], legend_offset=(10, 100), legend_position="right", line_alpha=0, padding=0.05, show_grid=True, show_legend=False, ylim=(0, None), )) hv.opts.defaults( hv.opts.BoxWhisker( box_cmap=default_categorical_cmap, box_fill_alpha=0.75, box_fill_color="lightgray", box_line_color="#222222", box_width=0.4, cmap=default_categorical_cmap, frame_height=300, frame_width=400, hooks=[no_xgrid_hook], legend_offset=(10, 100), legend_position="right", outlier_alpha=0.75, outlier_line_color=None, padding=0.05, show_grid=True, show_legend=False, toolbar="above", whisker_color="#222222", whisker_line_width=1, )) hv.opts.defaults( hv.opts.Curve( color=hv.Cycle(default_categorical_cmap), frame_height=300, frame_width=400, line_width=2, muted_line_alpha=0.1, padding=0.05, show_grid=True, toolbar="above", )) hv.opts.defaults(hv.opts.HeatMap(cmap=default_sequential_cmap)) hv.opts.defaults( hv.opts.HexTiles(cmap=default_sequential_cmap, padding=0.05, show_grid=True, toolbar="above")) hv.opts.defaults( hv.opts.Histogram( fill_alpha=0.3, fill_color=hv.Cycle(default_categorical_cmap), frame_height=300, frame_width=450, line_alpha=0, line_width=2, padding=0.05, show_grid=True, show_legend=True, toolbar="above", ylim=(0, None), )) hv.opts.defaults(hv.opts.Image(cmap=default_sequential_cmap)) hv.opts.defaults( hv.opts.NdOverlay( click_policy="hide", fontsize=dict(legend=8, title=12), legend_offset=(10, 100), legend_position="right", padding=0.05, show_grid=True, show_legend=True, toolbar="above", )) hv.opts.defaults( hv.opts.Overlay( click_policy="hide", fontsize=dict(legend=8), legend_offset=(10, 100), legend_position="right", padding=0.05, show_grid=True, show_legend=True, toolbar="above", )) hv.opts.defaults( hv.opts.Path( color=hv.Cycle(default_categorical_cmap), frame_height=300, frame_width=300, line_width=2, muted_line_alpha=0.1, padding=0.05, show_grid=True, toolbar="above", )) hv.opts.defaults( hv.opts.Points( alpha=0.75, cmap=default_categorical_cmap, color=hv.Cycle(default_categorical_cmap), fontsize=dict(legend=8), frame_height=300, frame_width=300, legend_offset=(10, 100), legend_position="right", padding=0.05, show_grid=True, show_legend=True, size=5, toolbar="above", )) hv.opts.defaults( hv.opts.Scatter( alpha=0.75, cmap=default_categorical_cmap, color=hv.Cycle(default_categorical_cmap), fontsize=dict(legend=8), frame_height=300, frame_width=400, legend_offset=(10, 100), legend_position="right", muted_line_alpha=0.1, padding=0.05, show_grid=True, size=5, toolbar="above", )) hv.opts.defaults( hv.opts.Spikes( cmap=default_categorical_cmap, color=hv.Cycle(default_categorical_cmap), fontsize=dict(legend=8), frame_height=300, frame_width=400, hooks=[no_xgrid_hook], line_width=2, muted_line_alpha=0.1, padding=0.05, show_grid=True, toolbar="above", ))
def plot_barchart(self): hv.extension('bokeh', logo=False) ##Stacked Bar chart for Day and Event Type self.events_day = self.data.groupby(by = ['start_day', 'events_type']).agg({'events_type':'count'}).rename( columns = {'events_type': 'Sessions'} ) self.events_day = self.events_day.reset_index() key_dimensions = [('start_day', 'Day'), ('events_type', 'Event')] value_dimensions = [('Sessions')] macro = hv.Table(self.events_day, key_dimensions, value_dimensions) self.bars = macro.to.bars(['Day', 'Event'], 'Sessions', []).options(stack_index= 1, width=1100, show_legend=False, height = 600, tools=['hover'], color = hv.Cycle('Category20')) bar_plot = renderer.get_plot(self.bars).state return bar_plot
pn.extension(comms="vscode") ## create random walks (one location) ## data_df = pd.DataFrame() npoints = 15000 np.random.seed(71) x = np.arange(npoints) y1 = 1300 + 2.5 * np.random.randn(npoints).cumsum() y2 = 1500 + 2 * np.random.randn(npoints).cumsum() y3 = 3 + np.random.randn(npoints).cumsum() data_df.loc[:, "x"] = x data_df.loc[:, "rand1"] = y1 data_df.loc[:, "rand2"] = y2 data_df.loc[:, "rand3"] = y3 colors = hv.Cycle("Category10").values dims = ["rand1", "rand2", "rand3"] items = [] for c, dim in zip(colors, dims): item = (data_df.hvplot(x="x", y=dim, kind="points", datashade=True, color=c).opts(height=200).hist(dim)) item[0].opts(datashade=True) item[1].opts(color=c) items.append(item) layout = hv.Layout(items) link_selections(layout).cols(1) data_df.hvplot(x="x", y=dim, kind="points", datashade=True)
def wrapper(self, *args, filepath=None, output='holoviews', img_format=None, always_save=False, backend=None, _compat_render=False, link_dataframes=None, cursor_delta=None, width=None, height=None, # Deprecated parameters rc_params=None, axis=None, interactive=None, colors: TypedList[str]=None, linestyles: TypedList[str]=None, markers: TypedList[str]=None, **kwargs ): def deprecation_warning(msg): warnings.warn( msg, DeprecationWarning, stacklevel=2, ) if interactive is not None: deprecation_warning( '"interactive" parameter is deprecated and ignored', ) interactive = is_running_ipython() # If the user did not specify a backend, we will return a # holoviews object, but we need to know what is the current # backend so we can apply the relevant options. if backend is None: backend = hv.Store.current_backend # For backward compat, return a matplotlib Figure when this # backend is selected if output is None and _compat_render and backend == 'matplotlib': output = 'render' # Before this point "None" indicates the default. if output is None: # TODO: Switch the default to be "ui" when interactive once a # solution is found for that issue: # https://discourse.holoviz.org/t/replace-holoviews-notebook-rendering-with-a-panel/2519/12 # output = 'ui' if interactive else 'holoviews' output = 'holoviews' # Deprecated, but allows easy backward compat if axis is not None: output = 'render' deprecation_warning( 'axis parameter is deprecated, use holoviews APIs to combine plots (see overloading of ``*`` operator for holoviews elements)' ) if link_dataframes and output != 'ui': warnings.warn(f'"link_dataframes" parameter ignored since output != "ui"', stacklevel=2) img_format = img_format or guess_format(filepath) or 'png' # When we create the figure ourselves, always save the plot to # the default location if filepath is None and always_save: filepath = self.get_default_plot_path( img_format=img_format, plot_name=f.__name__, ) # Factor the *args inside the **kwargs by binding them to the # user-facing signature, which is the one of the wrapper. kwargs.update( inspect.signature(wrapper).bind_partial(self, *args).arguments ) with lisa.notebook._hv_set_backend(backend): hv_fig = f(**kwargs) # For each element type, only set the option if it has not # been set already. This allows the plot method to give # customized options that will not be overridden here. set_by_method = {} for category in ('plot', 'style'): for name, _opts in hv_fig.traverse( lambda element: ( element.__class__.name, hv.Store.lookup_options( backend, element, category ).kwargs.keys() ) ): set_by_method.setdefault(name, set()).update(_opts) def set_options(fig, opts, typs): return fig.options( { typ: { k: v for k, v in opts.items() if k not in set_by_method.get(typ, tuple()) } for typ in typs }, # Specify the backend explicitly, in case the user # asked for a specific backend backend=backend, ) def set_option(fig, name, val, typs, extra=None): return set_options( fig=fig, opts={name: val, **(extra or {})}, typs=typs, ) def set_cycle(fig, name, xs, typs, extra=None): return set_option( fig=fig, name=name, val=hv.Cycle(xs), typs=typs, extra=extra, ) # Deprecated options if colors: deprecation_warning( '"colors" is deprecated and has no effect anymore, use .options() on the resulting holoviews object' ) if markers: deprecation_warning( '"markers" is deprecated and has no effect anymore, use .options() on the resulting holoviews object' ) if linestyles: deprecation_warning( '"linestyles" is deprecated and has no effect anymore, use .options() on the resulting holoviews object' ) if rc_params: deprecation_warning( 'rc_params deprecated, use holoviews APIs to set matplotlib parameters' ) if backend == 'matplotlib': hv_fig = hv_fig.opts(fig_rcparams=rc_params) else: self.logger.warning('rc_params is only used with matplotlib backend') # Markers added by lisa.notebook.plot_signal if backend == 'bokeh': marker_opts = dict( # Disable muted legend for now, as they will mute # everything: # https://github.com/holoviz/holoviews/issues/3936 # legend_muted=True, muted_alpha=0, tools=[], ) elif backend == 'matplotlib': # Hide the markers since it clutters static plots, making # them hard to read. marker_opts = dict( visible=False, ) else: marker_opts = {} hv_fig = set_options( hv_fig, opts=marker_opts, typs=('Scatter.marker',), ) # Tools if backend == 'bokeh': hv_fig = set_option( hv_fig, name='tools', val=[ 'undo', 'redo', 'crosshair', 'hover', ], typs=('Curve', 'Path', 'Points', 'Scatter', 'Bars', 'Histogram', 'Distribution', 'HeatMap', 'Image', 'Rectangles', 'Area', 'Spikes'), ).options( backend=backend, # Sometimes holoviews (or bokeh) decides to put it on # the side, which crops it toolbar='above', ) # Workaround: # https://github.com/holoviz/holoviews/issues/4981 hv_fig = set_option( hv_fig, name='color', val=hv.Cycle(), typs=('Rectangles',), ) # Figure size if backend in ('bokeh', 'plotly'): aspect = 4 if (width, height) == (None, None): size = dict( aspect=aspect, responsive=True, ) elif height is None: size = dict( width=width, height=int(width / aspect), ) elif width is None: size = dict( height=height, responsive=True, ) else: size = dict( width=width, height=height, ) hv_fig = set_options( hv_fig, opts=size, typs=('Curve', 'Path', 'Points', 'Scatter', 'Overlay', 'Bars', 'Histogram', 'Distribution', 'HeatMap', 'Image', 'Rectangles', 'Area', 'HLine', 'VLine', 'Spikes', 'HSpan', 'VSpan'), ) elif backend == 'matplotlib': width = 16 if width is None else width height = 4 if height is None else height fig_inches = max(width, height) hv_fig = set_options( hv_fig, opts=dict( aspect=width / height, fig_inches=fig_inches, ), typs=('Curve', 'Path', 'Points', 'Scatter', 'Overlay', 'Bars', 'Histogram', 'Distribution', 'HeatMap', 'Image', 'Rectangles', 'Area', 'HLine', 'VLine', 'Spikes'), ) # Not doing this on the Layout will prevent getting big # figures, but the "aspect" cannot be set on a Layout hv_fig = set_options( hv_fig, opts=dict(fig_inches=fig_inches), typs=('Layout',), ) # Use a memoized function to make sure we only do the rendering once @memoized def rendered_fig(): if backend == 'matplotlib': # Make sure to use an interactive renderer for notebooks, # otherwise the plot will not be displayed renderer = hv.plotting.mpl.MPLRenderer.instance( interactive=interactive ) return renderer.get_plot( hv_fig, interactive=interactive, axis=axis, fig=axis.figure if axis else None, ).state else: return hv.renderer(backend).get_plot(hv_fig).state def resolve_formatter(fmt): format_map = { 'rst': cls._get_rst_content, 'sphinx-rst': cls._get_rst_content, 'html': cls._get_html, 'sphinx-html': cls._get_html, } try: return format_map[fmt] except KeyError: raise ValueError(f'Unsupported format: {fmt}') if filepath: if backend in ('bokeh', 'matplotlib') and img_format in ('html', 'sphinx-html', 'rst', 'sphinx-rst'): content = resolve_formatter(img_format)( fmt=img_format, f=f, args=[], kwargs=kwargs, fig=rendered_fig(), backend=backend ) with open(filepath, 'wt', encoding='utf-8') as fd: fd.write(content) else: # Avoid cropping the legend on some backends static_fig = set_options( hv_fig, opts=dict(responsive=False), typs=('Curve', 'Path', 'Points', 'Scatter', 'Overlay', 'Bars', 'Histogram', 'Distribution', 'HeatMap', 'Image', 'Rectangles', 'HLine', 'VLine', 'VSpan', 'HSpan', 'Spikes'), ) hv.save(static_fig, filepath, fmt=img_format, backend=backend) if output == 'holoviews': out = hv_fig # Show the LISA figure toolbar elif output == 'ui': # TODO: improve holoviews so we can return holoviews # objects that are displayed with extra widgets around # https://discourse.holoviz.org/t/replace-holoviews-notebook-rendering-with-a-panel/2519/12 make_pane = functools.partial( self._make_fig_ui, link_dataframes=link_dataframes, ) out = _hv_fig_to_pane(hv_fig, make_pane) elif output == 'render': if _compat_render and backend == 'matplotlib': axes = rendered_fig().axes if len(axes) == 1: out = axes[0] else: out = axes else: out = rendered_fig() else: out = resolve_formatter(output)( fmt=output, f=f, args=[], kwargs=kwargs, fig=rendered_fig(), backend=backend ) return out