def plot_overview(): produccion = serie_campo.groupby(by='fecha').mean() estado_mecanico = serie_status elementos_status = dict(status=pd.unique(estado_mecanico.estado_actual),numero=estado_mecanico.estado_actual.value_counts()) elementos_trayectoria = dict(trayectoria=pd.unique(estado_mecanico.trayectoria),numero=estado_mecanico.trayectoria.value_counts()) elementos_pozos = dict(indice=resumen.index[0:6], valores=resumen[0:6]) elementos_volumen = dict(indice=resumen.index[13:], valores=resumen[13:]) tabla_pozos = hv.Table(elementos_pozos,'indice','valores') tabla_pozos.opts(height=500,fontscale=20) tabla_volumen = hv.Table(elementos_volumen,'indice','valores') tabla_volumen.opts(height=500,fontscale=20) plot_prod_aceite = hv.Curve(produccion, 'fecha', 'aceite_Mbd',label='Aceite Mbd') plot_prod_gas = hv.Curve(produccion,'fecha','gas_asociado_MMpcd',label='Gas Asociado MMpcd') plot_produccion = plot_prod_aceite * plot_prod_gas plot_produccion.opts(width=600, fontscale=1.5) plot_trayectoria = hv.Bars(elementos_trayectoria,'trayectoria','numero') plot_trayectoria.opts(stacked=True, color='trayectoria', cmap='Spectral', invert_axes=True, fontscale=1.5, yaxis=None) #fill_color=factor_cmap('trayectoria', palette=Spectral6, factors=elementos_trayectoria['trayectoria'])) plot_status = hv.Bars(elementos_status,'status','numero') plot_status.opts(stacked=True, color='status', fill_color=factor_cmap('status', palette=Spectral6, factors=elementos_status['status']), xrotation=90, invert_axes=True, fontscale=1.5, xticks=None, yaxis=None) row1 = tabla_pozos + plot_status + plot_trayectoria row2 = tabla_volumen + plot_produccion fig1 = hv.render(row1) hv.output(row1, backend='bokeh', fig='html', size=200) fig2 = hv.render(row2) hv.output(row2, backend='bokeh', fig='html', size=200) return
def main(): """A Reactive View of the KickstarterDashboard""" kickstarter_df = get_kickstarter_df() kickstarter_dashboard = KickstarterDashboard(kickstarter_df=kickstarter_df) st.markdown(__doc__) st.info(INFO) options = get_categories() categories_selected = st.multiselect("Select Categories", options=options) if not categories_selected and kickstarter_dashboard.categories: kickstarter_dashboard.categories = [] else: kickstarter_dashboard.categories = categories_selected st.sidebar.title("Selections") x_range = st.sidebar.slider("Select create_at range", 2009, 2018, (2009, 2018)) y_range = st.sidebar.slider("Select usd_pledged", 0.0, 5.0, (0.0, 5.0)) filter_df = KickstarterDashboard.filter_on_categories( kickstarter_df, categories_selected) filter_df = kickstarter_dashboard.filter_on_ranges( filter_df, (pd.Timestamp(x_range[0], 1, 1), pd.Timestamp(x_range[1], 12, 31)), y_range) kickstarter_dashboard.scatter_df = filter_df st.bokeh_chart(hv.render(kickstarter_dashboard.scatter_plot_view())) st.bokeh_chart(hv.render(kickstarter_dashboard.bar_chart_view()))
def save_holoviews(fpath, obj, save_components=False, save_doc=False, save_html=True, save_pickle=False, save_item=False): from holoviews.core.io import Pickler import holoviews as hv obj.opts(title="") if fpath.endswith('.html'): fpath = ".".join(fpath.split(".")[:-1]) if save_pickle: print("saving {}.hvz".format(fpath)) with open(fpath + '.hvz', 'wb') as f: Pickler.save(obj, f) if save_item: print("saving {}-item.json".format(fpath)) from bokeh.embed import json_item p = hv.render(obj, backend='bokeh') item_json = json_item(p) with open(fpath + '-item.json', 'w') as f: json.dump(item_json, f, indent=2) if save_doc: print("saving {}-doc.json".format(fpath)) from bokeh.document import Document p = hv.render(obj, backend='bokeh') doc = Document() doc.add_root(p) doc_json = doc.to_json() with open(fpath + '-doc.json', 'w') as f: json.dump(doc_json, f, indent=2) if save_components: print("saving {}.{{script|div}}".format(fpath)) from bokeh.embed import components p = hv.render(obj, backend='bokeh') script, div = components(p) with open(fpath + '.script', 'w') as f: f.write(script) with open(fpath + '.div', 'w') as f: f.write(div) if save_html: print("saving {}.html".format(fpath)) hv.save(obj, fpath + ".html")
def main(npz_filepath, out): assert out[-5:] == ".html", "Please enter an html output file" data = np.load(npz_filepath) widgets = [] widgets += [ Div(text="<h1>NPZ statistic</h1><b>Subfiles found</b></br>{}".format( data.files)) ] output_file(out, title="NPZ statistic") for subfile in data.files: subdata = data[subfile].squeeze() array_repr = subdata.__str__() array_describe = pformat(dict(describe(subdata)._asdict())) if subdata.ndim == 1: hist, edges = np.histogram(subdata) hv_hist = hv.Histogram((edges, hist)) hv_hist.opts(tools=["hover"], title=subfile + " histogram", width=600) fig = hv.render(hv_hist) elif subdata.ndim == 2: heatmap = hv.Image(subdata) heatmap.opts(colorbar=True, width=600, height=600, tools=["hover"], title=subfile) fig = hv.render(heatmap) else: fig = Div(text="To many dimension to visualize") annotation = ("<h2>{}</h2>" "<b>Overview</b></br>{}</br>{}</br>" "<b>Describe</b></br>{}</br>").format( subfile, subdata.shape, array_repr, array_describe) annotation = annotation.replace("\n", "</br>") html_annotation = Div(text=annotation) widgets += [row([fig, html_annotation])] data.close() show(column(*widgets))
def histogram(data_frame, column_name, num_bins, x_label=None, y_label=None, title=None): """ Creates a histogram of the column in the input data frame. :param data_frame: pandas data frame :param column_name: column in data frame :param num_bins: number of bins to divide data into for histogram :return: bokeh figure object """ hv_plot_object = data_frame.hvplot.hist(column_name, bins=num_bins, height=400, tools="", xlabel=x_label, ylabel=y_label, title=title, fill_alpha=0.5) bokeh_plot = hv.render(hv_plot_object) style(bokeh_plot) return bokeh_plot
def plot_sensitivities(df_tidy, name = 'H', logx = True, plot_abs = False, param = 'N'): df_tidy_n = df_tidy.loc[df_tidy['species'] == name, :] plots = [] for sense in [param, 'gamma']: df_small = df_tidy_n.loc[df_tidy_n['sensitivity_to'] == sense, :] if plot_abs: df_small['abs_sensitivity'] = np.abs(df_small['sensitivity'].values) points = hv.Points( data=df_small, kdims=[param, 'abs_sensitivity'], vdims=['gamma'], ) else: points = hv.Points( data=df_small, kdims=[param, 'sensitivity'], vdims=['gamma'], ) points.opts(color = 'gamma', cmap = 'Purples', logx = logx, title = sense, colorbar = True, size= 7, frame_height=200, frame_width=200 * 3 // 2,) p = hv.render(points) plots.append(p) return plots
def plot(self, doc): import holoviews as hv if doc.roots: doc.clear() self._reproject_ranges() self._progress_callback(10) hvPlot = self.compose_overlay_plot(self._x_range, self._y_range) if self._preload_complete: self._progress_bar_callback(100) fig = hv.render(hvPlot, backend='bokeh') fig.output_backend = 'webgl' def update_range(n, val): if n == 'x0': self._x_range[0] = round(val, 2) elif n == 'x1': self._x_range[1] = round(val, 2) elif n == 'y0': self._y_range[0] = round(val, 2) elif n == 'y1': self._y_range[1] = round(val, 2) fig.x_range.on_change('start', lambda attr, old, new: update_range('x0', new)) fig.x_range.on_change('end', lambda attr, old, new: update_range("x1", new)) fig.y_range.on_change('start', lambda attr, old, new: update_range("y0", new)) fig.y_range.on_change('end', lambda attr, old, new: update_range("y1", new)) doc.add_root(fig) self._current_plot = doc
def show_pre_and_tmp(self): """Shows the annual temperature and precipitation cycle. Renders the holoviews curve of temperature and the holoviews bars of precipitation in a new webpage. """ show(hv.render(self.combined(self._lon, self._lat)))
def export_svg(plot, fname): ''' This doesn't work. It would be very useful. ''' ''' export holoview object to filename fname ''' from bokeh.io import export_svgs p = hv.render(plot, backend='bokeh') p.output_backend = "svg" export_svgs(p, filename=fname)
def main(): st.title('Figurinhas!!') st.write( "Vamos analisar a nossa rede sociais de participantes das figurinhas..." ) people = get_people() data = get_netdata() option = st.selectbox('Gostaria de ver a rede de qual jogador?', ['None'] + people['user'].tolist()) if option != "None": 'Você selecionou: ', option, "\n\nConfira as informações básicas deste usuário:\n" st.table(people[people['user'] == option].rename( columns={ "user": "******", "qtde_relacionamentos": "Relacionamentos", "qtde_figurinhas": "Figurinhas Trocadas" })) simple_graph = get_user_network(data, option) else: st.dataframe( people.rename( columns={ "user": "******", "qtde_relacionamentos": "Relacionamentos", "qtde_figurinhas": "Figurinhas Trocadas" })) simple_graph = make_network(data) st.bokeh_chart(hv.render(simple_graph, backend='bokeh'), use_container_width=True)
def time_plot(df, p1, p2, logx=True): points = hv.Points( data=df, kdims=[p1, 'time'], vdims=[p2], ) if logx: points.opts( color=p2, cmap='Reds', logx=True, title='time to ss', colorbar=True, size=7, frame_height=200, frame_width=200 * 3 // 2, ) else: points.opts( color=p2, cmap='Reds', title='time to ss', colorbar=True, size=7, frame_height=200, frame_width=200 * 3 // 2, ) p = hv.render(points) return p
def make_smallplot(df_tidy, names, p1, p2, name='H', to_plot='concentration', logx=True): df_small = df_tidy.loc[df_tidy['species'] == name, :] points = hv.Points(data=df_small, kdims=[p1, to_plot], vdims=[p2]) if logx: points.opts( color=p2, cmap='Blues', logx=True, title=name, colorbar=True, size=7, frame_height=200, frame_width=200 * 3 // 2, ) else: points.opts( color=p2, cmap='Blues', title=name, colorbar=True, size=7, frame_height=200, frame_width=200 * 3 // 2, ) p = hv.render(points) return p
def make_gridplot(df_tidy, names, p1, p2, to_plot = 'concentration', logx = True, yrange = bokeh.models.Range1d(0, 15)): plots = [] for name in names: df_small = df_tidy.loc[df_tidy['species'] == name, :] points = hv.Points( data=df_small, kdims=[p1, to_plot], vdims=[p2], ) if logx: points.opts(color = p2, cmap = 'Blues', logx=True, title = name, colorbar = True, size= 7, frame_height=200, frame_width=200 * 3 // 2,) else: points.opts(color = p2, cmap = 'Blues', title = name, colorbar = True, size= 7, frame_height=200, frame_width=200 * 3 // 2,) # curve = hv.Curve(data = df_small, kdims=[p1, "concentration"], # vdims=[p2]).opts(logx=True,frame_height=200, frame_width=200 * 3 // 2) # overlay = hv.Overlay([points, curve]) p = hv.render(points) if name == 'H': p.y_range = yrange plots.append(p) return bokeh.layouts.gridplot(plots, ncols = 2)
def boxplot_metrics(data, title, color_by='Method', palette='Set3', invert_xaxis=True): data = data.melt(var_name='Variables', value_name='Metric Value') data['Method'] = data['Variables'].apply(lambda x: x.split('-')[0]) data['Ranking'] = data['Variables'].apply(lambda x: x.split('-')[1]) data['Metric'] = data['Variables'].apply(lambda x: x.split('-')[2]) boxwhisker = hv.BoxWhisker(data, ['Metric', 'Ranking', 'Method'], 'Metric Value', label=title) boxwhisker.opts(show_legend=False, width=900, height=500, box_fill_color=color_by, cmap=palette, ylim=(0, 1), xrotation=45, invert_xaxis=invert_xaxis, toolbar='above') f = hv.render(boxwhisker, backend='bokeh') f.toolbar.logo = None f.grid.grid_line_color = 'lightgrey' f.grid.grid_line_dash = [5, 3] return f
def box_plot_max_ranges(data_frame, output_channels_needed, x_label=None, y_label=None, title=None): """ Creates a figure with n boxplots that can be most sensitive to outliers. :param data_frame: pandas dataframe object :param described_df: pandas dataframe object with a max and min column :param largest_ranges_n: number of boxplots to be made :return: a boxplot figure that has n boxplots with the largest range """ # CLEAN THIS UP data_frame.columns = data_frame.columns.map(str) max_range_df = data_frame[output_channels_needed] columns = list(max_range_df.columns) plot = max_range_df.hvplot.box(y=columns, legend=False, invert=False, box_fill_alpha=0.5, outlier_fill_color="red", outlier_alpha=0.3, width=1200, height=600, xlabel=x_label, ylabel=y_label, title=title) bokeh_plot = hv.render(plot) style(bokeh_plot) return bokeh_plot
def save_bokeh_svg(obj, fname): if not fname[-4:] == '.svg': fname += '.svg' plot = render(obj) figs = list(plot.select(dict(type=Figure))) for k, _ in enumerate(figs): figs[k].output_backend = 'svg' return export_svgs(plot, filename=fname)
def figure(self) -> bokeh.plotting.Figure: """The Figure to plot""" if self._figure is None: if self.plot.__module__.startswith("holo"): self._figure = holoviews.render(self.plot) else: self._figure = self.plot return self._figure
def alpha_beta_plotter(df_conc, dot_alpha = 0.5, dot_size = 1.5): """ Function to plot the alpha vs beta parameters for bootstrapped samples for all Tubulin concentration values. Parameters ---------- df_conc : pandas DataFrame DataFrame containing the bootstrapped parameter values. dot_alpha : float Alpha value for the plot dots dot_size : float Size of the glyphs. Returns ------- alpha_beta_plot : figure bokeh figure of alpha-beta scatter plots. """ # Creating scatterplot alpha_beta = hv.Scatter( data = df_conc, kdims = ["Alpha_MLE", "Beta_MLE"], vdims = ["Concentration (uM)"], ).opts( height = 750, width = 750, legend_position = "right", color = "Concentration (uM)", title = "Alpha_MLE vs Beta_MLE", size = dot_size, alpha = dot_alpha, ).groupby( "Concentration (uM)" ).overlay( ) alpha_beta.opts(legend_position = "right") # Rendered alpha_beta_plot = hv.render(alpha_beta) # Aligning the title t = Title() t.text = "Alpha_MLE vs Beta_MLE" alpha_beta_plot.title = t alpha_beta_plot.title.align = "center" # Setting the legend labels alpha_beta_plot.legend.title = "Concentration (uM)" return alpha_beta_plot
def chordDiagram(person_id, df_enron): import holoviews as hv from holoviews import opts from bokeh.resources import CDN from bokeh.embed import file_html hv.extension('bokeh') df_chord = df_enron.sort_values('fromJobtitle') df_chord['index'] = df_chord.index df_links = df_chord.groupby(['fromId', 'toId']).agg({ 'date': 'count', 'sentiment': 'mean' }) df_links = df_links.reset_index()[['fromId', 'toId', 'date', 'sentiment']] df_links.columns = ['source', 'target', 'value', 'sentiment'] x = df_chord[['fromId', 'fromJobtitle']].drop_duplicates() x.columns = ['source', 'fromJobtitle'] df_links = pd.merge(df_links, x, on="source") df_links.drop_duplicates(subset='source') df_nodes = df_chord[['fromId', 'fromEmail', 'fromJobtitle' ]].drop_duplicates().reset_index(drop=True) df_nodes.columns = ['index', 'name', 'group'] df_nodes.sort_values('name') y = df_chord[['fromId', 'toId']].drop_duplicates().groupby(['fromId' ]).count().reset_index() y.columns = ['index', 'size'] df_nodes = pd.merge(df_nodes, y, on='index') df_nodes['size'] = df_nodes['size'] / 3 + 8 nodes = hv.Dataset(df_nodes, 'index') edge_df = df_links import seaborn as sns # also improves the look of plots sns.set() # set Seaborn defaults chord = hv.Chord((df_links, nodes)).select(value=(5, None)) chord.opts( opts.Chord(cmap='Category20', edge_cmap='Category20', edge_color='sentiment', labels='name', node_color='group', edge_alpha=0.8, edge_line_width=1.5)) final_chord = chord.select(index=person_id) plot = hv.render(final_chord, backend='bokeh') item_text = json.dumps(json_item(plot)) return item_text
def moves(self, moves_list): log.info("Generating moves...") df = pd.DataFrame(moves_list, columns=['from', 'to', 'value']) fig = hv.render( hv.Sankey(moves_list, ['from', 'to'], vdims='value').opts(cmap='Dark2', edge_color='to', node_color='index')) self.pdf.savefig(fig) return self
def hv_plot_param(df_tidy, species='H', param='N'): hv_fig = hv.Curve( df_tidy, kdims=['time', species], vdims=[param], ).groupby(param).overlay().opts(frame_height=250, frame_width=250 * 3 // 2) hv_fig.opts(opts.Curve(color=hv.Palette('Viridis'), width=600)) # Take out the Bokeh object p = hv.render(hv_fig) return p
def main(): print("Conecatando...", end="") conn = open_db() print("Ok.") query = import_query(os.path.join(SRC_DIR, "query.sql")) df = pd.read_sql_query(query, conn) G = nx.from_pandas_edgelist(df, source='user_a', target='user_b') st.bokeh_chart(hv.render(G, backend='bokeh'))
def map(_id): ds = load_file(_id) lon, lat = get_lon_lat_names(_id) plot = ds.hvplot(x=lon, y=lat).opts(responsive=True, cmap="terrain") plot = hv.render(plot, backend="bokeh") plot.sizing_mode = "scale_width" script, div = components(plot) return render_template("app/map.html", script=script, div=div, data_file_id=_id)
def bokeh_main_2(): import sys src = Path(__file__).absolute().parent / 'src' sys.path.insert(0, str(src)) from bokeh.layouts import layout # type: ignore from bokeh.models.widgets import Tabs, Panel # type: ignore from bokeh.plotting import figure # type: ignore from dashboard.core.bokeh import test_scatter_matrix import holoviews as hv f1 = hv.render(test_scatter_matrix()) f2 = figure() f2.circle([0, 0, 2], [4, -1, 1]) # todo need something more lazy? from dashboard.data import sleep_dataframe from dashboard.sleep import plot_sleep # TODO would be cool to display logs in the frontend and also currently evaluated function? # although pehaps it's easier to just always keep logs open? from bokeh.models.widgets import DateRangeSlider # type: ignore from datetime import date drs = DateRangeSlider( title="Date Range: ", start=date(2017, 1, 1), end=date.today(), value=(date(2017, 9, 7), date(2017, 10, 15)), step=1, ) def update(attr, old, new): print(attr, old, new) from bokeh.models import CustomJS # type: ignore # todo see https://docs.bokeh.org/en/latest/docs/gallery/slider.html update_js = CustomJS(args=dict(drs=drs), code=''' console.log("HIIII"); ''') drs.on_change('value', update) drs.js_on_change('value', update_js) l1 = layout([[f1, drs]], sizing_mode='fixed') l2 = layout([[f2]], sizing_mode='fixed') tabs = Tabs(tabs=[ Panel(child=l1, title='This is Tab 1'), Panel(child=l2, title='This is Tab 2'), # Panel(child=layout([[sp]]), title='Sleep dataframe'), ]) curdoc().add_root(tabs)
def plot_chordgraph(G, node_data=None, label_col='index', size=200, cmap='Category20', title='', draw_labels=True, edge_color='E-Group', node_color='index'): hv.extension('bokeh') hv.output(size=size) # Get the edge list of the graph H = nx.to_undirected(G) edge_data = nx.to_pandas_edgelist(H) # Enforce that the value column is in the right position in the dataframe print(edge_data.columns) val_loc = 2 cur_loc = edge_data.columns.get_loc("value") cols = list(edge_data.columns.values) swap = cols[val_loc] cols[val_loc] = cols[cur_loc] cols[cur_loc] = swap edge_data = edge_data.reindex(columns=cols) # Account for passed in node dataset if node_data is not None: node_dataset = hv.Dataset(node_data, 'index') chord = hv.Chord((edge_data, node_dataset), label=title).select(value=(5, None)) else: chord = hv.Chord(edge_data, label=title) label_col = 'index' # Draw the desired graph if draw_labels is True: chord.opts( hv.opts.Chord( cmap=cmap, edge_cmap=cmap, edge_color=hv.dim(edge_color).str(), node_color=hv.dim(node_color).str(), labels=label_col, )) else: chord.opts( hv.opts.Chord(cmap=cmap, edge_cmap=cmap, edge_color=hv.dim(edge_color).str(), node_color=hv.dim(node_color).str())) c = hv.render(chord, backend='bokeh') return c
def show_results(self): """This function shows all results form all analyses""" for plot in self.plotObjects: if "All" in plot: if self.backend == "matplotlib": renderer = hv.renderer(self.backend) renderer.show(plot["All"]) if self.backend == "bokeh": finalfig = hv.render(plot["All"], backend="bokeh") show(finalfig) sleep(1.0) else: self.log.info("No 'all' plot defined, skipping...")
def show_results(self): """This function shows all results form all analyses""" if self.backend == "bokeh": self.log.info("Showing the 'all' plot from every analysis...") for plot in self.plotObjects: if "All" in plot: finalfig = hv.render(plot["All"], backend='bokeh') show(finalfig) sleep(1.) else: self.log.info("No 'all' plot defined, skipping...") else: self.log.error( "Showing all results only possible with bokeh backend...")
def bokeh_fig(year): df = gapminder.query("year == %d" % (year or 1952)) return json_item( hv.render( hv.Points(df, kdims=["gdpPercap", "lifeExp"]).opts(color="continent", size=hv.dim("pop")**(0.5) / 800, logx=True, height=330, width=530, cmap="Category10", tools=["hover"], legend_position="bottom_right", title="HoloViews / Bokeh")))
def main(json_path: str, type_: str, out: str): assert out[-5:] == ".html" if type_ == "f": assert json_path[-5:] == ".json" list_json_paths = [Path(json_path)] else: list_json_paths = list(Path(json_path).glob("**/*.json")) all_data: list = [] for pathfile in list_json_paths: with open(pathfile) as json_file: data = json.load(json_file) dictionary = {} for k, v in data.items(): if type(v) == int or type(v) == float: dictionary[k] = v elif type(v) == bool: dictionary[k] = int(v) all_data += [dictionary] df = pd.DataFrame(all_data) widgets: list = [] for column_name in df.columns: data = df[column_name].values frequencies, edges = np.histogram(data) hist = hv.Histogram((edges, frequencies)) hist.opts(tools=["hover"], title=column_name, width=600) annotation = ("<h2>{}</h2>" "<b>Overview</b></br>{}</br>{}</br>" "<b>Describe</b></br>{}</br>").format( column_name, data.shape, np.array_repr(data), pformat(dict(describe(data)._asdict())), ) annotation = annotation.replace("\n", "</br>") html_annotation = Div(text=annotation) widgets.append(row(hv.render(hist), html_annotation)) layout = column(*widgets) output_file(out, title=out) save(layout)
def plot_gasto_inicial(): dispersion_qi = hv.Points(tipos,kdims=['first_oil','Qi_hist']) dispersion_qi.opts(width=600, size=20, color='tipo', cmap='Set1', fontscale=1.5, legend_position='top') fig = hv.render(dispersion_qi) hv.output(dispersion_qi, backend='bokeh', fig='html', size=200) return
def hv_plot(df_tidy, to_plot='all'): if to_plot == 'all': hv_fig = hv.Curve(df_tidy, kdims=['time', 'concentration'], vdims=['species']).groupby('species').overlay().opts( frame_height=250, frame_width=250 * 3 // 2) else: df_small = df_tidy.loc[df_tidy['species'].isin(to_plot), :] hv_fig = hv.Curve(df_small, kdims=['time', 'concentration'], vdims=['species']).groupby('species').overlay().opts( frame_height=250, frame_width=250 * 3 // 2) # Take out the Bokeh object p = hv.render(hv_fig) return p