def main(method_num): # Method 1: Quickly create a web visualization with Python back-end # support. if method_num == 1: # NOTE: Documentation states, "Initializes the pyviz notebook extension # to allow plotting with bokeh and enable comms." It seems that # `panel.extension` is not required when generating web # visualizations with the `.show()` method. pn.extension() pn.interact(panel_wrapper).show() # Method 2: Adjust the layout of the quick creation in Method 1. if method_num == 2: i = pn.interact(panel_wrapper) text = "<br>\n# Random Walk as a Function of Standard Deviation" p = pn.Row(i[1][0], pn.Column(text, i[0][0])) p.show() # Method 3, 4, & 5: Explicitly build the panel objects. if method_num == 3 or method_num == 4 or method_num == 5: c_opts = ["default", "optimized", "calibrated", "variable"] dummy_catagory = pn.widgets.RadioButtonGroup(name="dummy_catagory", value="default", options=c_opts) stdev = pn.widgets.FloatSlider(name="stdev", value=0.03, start=0, end=0.1, step=0.01) @pn.depends(stdev, dummy_catagory) def reactive_panel(stdev, dummy_catagory): return panel_wrapper(stdev, dummy_catagory) text = "<br>\n# Random Walk as a Function of Standard Deviation" widgets = pn.Column(text, stdev, dummy_catagory) p_rw = pn.Row(reactive_panel, widgets) # Method 3: Deploy a web visualization with a Python server. if method_num == 3: p_rw.show() # Method 4: Deploy a web visualization with data embedded in HTML. # NOTE: This stand alone version works with the following web browsers: # - Chrome Version 80.0.3987.122 # - Microsoft Edge 41.16299.1480.0 # This stand alone version does not work with the following web # browsers: # - Internet Explorer Version 11.1685.16299.0. if method_num == 4: f_out = "test.html" p_rw.save(f_out, title="This is a test", embed=True, max_opts=10) # Method 5: Deploy a web visualization referencing json data files. if method_num == 5: f_out = "test_json.html" p_rw.save(f_out, title="This is a test", embed=True, max_opts=10, embed_json=True) return 0
def interactive_logistic_regression(X, y, target_names=None, feature_names=None, stacked: bool = False): from panel import widgets import panel as pn X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42) embedding = umap.UMAP(n_components=2, random_state=160290).fit_transform( np.concatenate([X_train, X_test])) def interactive_model(C, penalty, fit_intercept, intercept_scaling, l1_ratio, class_weight): model = LogisticRegression( C=C, penalty=penalty, solver="saga", fit_intercept=fit_intercept, intercept_scaling=intercept_scaling, l1_ratio=l1_ratio, class_weight=class_weight, random_state=42, ).fit(X, y) return plot_model_evaluation( model, X_train, y_train, X_test, y_test, target_names=target_names, feature_names=feature_names, stacked=stacked, embedding=embedding, ) c_slider = widgets.LiteralInput(value=1, name="C") penalty_tog = widgets.RadioButtonGroup( name="penalty", options=["none", "l1", "l2", "elasticnet"]) fit_intercept = widgets.Toggle(name="fit_intercept") intercept_scaling = widgets.LiteralInput(value=1, name="intercept_scaling") l1_ratio = widgets.FloatSlider(end=1.0, start=0.0, value=0.5, name="l1_ratio") class_weight = widgets.LiteralInput(value=None, name="class_weight") return pn.interact( interactive_model, C=c_slider, penalty=penalty_tog, fit_intercept=fit_intercept, intercept_scaling=intercept_scaling, l1_ratio=l1_ratio, class_weight=class_weight, )
def plot(self): def interact_frame(time_stamp=0): plot_title = 'Time: ' + str(self.time_stamps[time_stamp]) + ' min' return hv.Points(data=self.dfs[time_stamp], kdims=[('Potential', 'Potential [V]'), ("Diff", "Current [A]")], vdims=['Time Stamp']).opts(tools=['hover'], title=plot_title) plot = pn.interact(interact_frame, time_stamp=(0, len(self.time_stamps) - 1)) return plot
def create_dashboard(): mgrDir_list = ['Manager', 'Director'] mgrDirWidget = pn.interact(mgrDir, ManagerDirector=mgrDir_list) assignmentsWidget = pn.interact( chooseAssignmentLevel, Quarter_Detail=['With_Quarters', 'Without_Quarters'], ManagerDirector=mgrDir_list) managerJobsWidget = pn.interact(displayManagerJobs, Manager=df['Manager'].unique(), ManagerDirector=mgrDir_list) gspec = pn.GridSpec(sizing_mode='stretch_both', max_height=800) gspec[0, :2] = pn.Row("# Novak Francella Manager/Partner Hours") gspec[1:4, 0] = mgrDirWidget gspec[1:6, 1] = pn.Column('') gspec[1:3, 2] = assignmentsWidget gspec[1:6, 3] = pn.Column('') gspec[1:6, 4] = managerJobsWidget return gspec
def main(): dir_name = setup() print('\n', 'Start of main', '\n') p = Path('extract_dir') p.mkdir(exist_ok=True) demux = dir_name + '/demux.qzv' print(demux) data_zip = zipfile.ZipFile(demux, 'r') data_zip.extractall(path='extract_dir') # potential to add a RegEx condition to create extract_dir based # on input files or directory for file in glob.iglob('extract_dir/*/data/per-*.csv'): print(file) data = pd.read_csv(file) data.head() fig = px.bar(data, x='Sample name', y='Sequence count', title='test graph') # HIDE FOR NOW fig.show() fig1 = go.Figure( go.Scatter(x=data['Sample name'], y=data['Sequence count'], name='test graph object')) fig1.update_layout(title='Demux data', plot_bgcolor='rgb(230,200,170)', showlegend=True) # HIDE FOR NOW fig1.show() print(type(data)) #produces <class 'pandas.core.frame.DataFrame'> df_widget = pn.widgets.DataFrame(data, name='DataFrame') df_widget.show() ###PANEL MODULE def select_row(row=0): return data.loc[row] slide = pn.interact(select_row, row=(0, len(data) - 1)) # THIS STOPS EXECUTION --> slide.show() # slide1 = pn.interact(select_row, row=(0, 25)) # slide1.show() #slide.servable() # FOR USE WITH 'panel serve' command on notebook file .ipynb # this above call should also work for .py files tutorial(dir_name)
def plot_DEM_difference(data, histogram='ground_track', scatter='longitude', bins=100, subplots=False): """ Panel to explore pointwise differences with ArcticDEM Includes a histogram, a scatter plot, and a summary table """ # Static plot def difference(data=data, histogram=histogram, scatter=scatter): plot_hist = data.hvplot.hist('height_diff', bins=bins, by=histogram, subplots=subplots, alpha=0.5) plot_scat = data.hvplot.scatter(scatter, 'height_diff', size=1, alpha=0.1) return (pn.Column(plot_scat, plot_hist)) # Widget values kw = dict(histogram=[ 'ground_track', 'atl06_quality_summary', 'bsnow_conf', 'bsnow_h', 'bsnow_od', 'cloud_flg_asr', 'cloud_flg_atm', 'msw_flag', 'layer_flag' ], scatter=[ 'segment_id', 'latitude', 'longitude', 'h_li', 'n_fit_photons', 'w_surface_window_final', 'n_fit_photons_ratio_w', 'bckgrd', 'dem_h', 'geoid_h' ]) # Interactive plot i = pn.interact(difference, **kw) # Layout df = pd.DataFrame(data.height_diff.describe()) text = "<br>\n# Difference in estimated height with ArcticDEM" p = pn.Row(pn.Column(text, i[0][1], i[0][0], df), pn.Column(i[1][0])) return (p)
def plot_daily(data, day=None, col='ground_track'): """ Panel with daily plots: lat vs lon (map view), and height vs lat (profile view) Interactivity on day and color """ # Static plot def daily_scatter(data=data, day=day, col='ground_track'): mapp = data[data.loc[:, 'time'].dt.date == day].hvplot.scatter( x='longitude', y='latitude', s=0.2, c='h_li', alpha=0.2, cmap='viridis') scatter = data[data.loc[:, 'time'].dt.date == day].hvplot.scatter( x='latitude', y='h_li', s=0.2, c=col) global lat_bounds lat_bounds = BoundsX( source=scatter) # select box to define area for external data return (pn.Column(mapp, scatter)) # Widget values kw = dict(col=sorted(list(data.columns)), day=data['time'].dt.date.unique()) global im # used to extract selected day and retrieve external data # Interactive plot im = pn.interact(daily_scatter, **kw) # Layout text = "<br>\n# Daily ATL06 data for the selected area\nSelect a day and a color variable" p = pn.Row(pn.Column(text, im[0][1], im[0][0]), im[1][0]) return (p)
rus = RandomUnderSampler(random_state=2019) X, y = rus.fit_resample(train.drop("validation", axis=1), train.validation) train_clas = pd.DataFrame(X) train_clas["4"] = y train_clas.columns = df.columns pn.extension() pn.extension('katex') def select_row(row=0): return df[df.index == row] pn.interact(select_row, row=(0, len(df) - 1)) # Language model data data_lm = TextLMDataBunch.from_df(".", train, val, text_cols="direction_list", mark_fields=False) # Classifier model data data_clas = TextClasDataBunch.from_df( ".", train_clas, val, text_cols="direction_list", label_cols="validation", vocab=data_lm.train_ds.vocab,
return x, y #================================================================================================= def Clifford_plot(x0=0, y0=0, n=100000, a=1.6, b=-0.7, c=-1.8, d=-1.9, cmap=["pink", "purple"]): cvs = ds.Canvas(plot_width=700, plot_height=700) x, y = Clifford_trajectory(x0, y0, n, a, b, c, d) agg = cvs.points(pd.DataFrame({'x': x, 'y': y}), 'x', 'y') return tf.shade(agg, cmap) #================================================================================================= pn.extension() pn.interact(Clifford_plot, n=(1, 1000000)) #================================================================================================= # The value of this attractor can be changed freely. Try it in the jupyter notebook.
) # %% # Interactive holoviews scatter plot to find referencegroundtrack needed # Tip: Hover over the points, and find those with high 'dhdt_slope' values layout: pn.layout.Column = pn.interact( dhdt_plot, cycle=pn.widgets.IntSlider(name="Cycle Number", start=2, end=7, step=1, value=7), dhdt_variable=pn.widgets.RadioButtonGroup( name="dhdt_variables", value="dhdt_slope", options=["referencegroundtrack", "dhdt_slope", "h_corr"], ), dhdt_range=pn.widgets.RangeSlider(name="dhdt range ±", start=0, end=20, value=(1, 10), step=0.5), rasterize=pn.widgets.Checkbox(name="Rasterize"), datashade=pn.widgets.Checkbox(name="Datashade"), ) dashboard: pn.layout.Column = pn.Column( pn.Row( pn.Column(layout[0][1], align="center"), pn.Column(layout[0][0], layout[0][2], align="center"), pn.Column(layout[0][3], layout[0][4], align="center"), ),
x, y = np.zeros(n), np.zeros(n) x[0], y[0] = x0, y0 for i in np.arange(n - 1): x[i + 1] = y[i] - np.sqrt(abs(b * x[i] - c)) * np.sign(x[i]) y[i + 1] = a - x[i] return x, y #--------------------------------------------------------------------------------- def hopalong1_plot(a=1.000, b=2.000, c=6.600, n=4000000, colormap=ps['fire']): cvs = ds.Canvas(plot_width=500, plot_height=500) x, y = hopalong1_trajectory(a, b, c, 0, 0, n) agg = cvs.points(pd.DataFrame({'x': x, 'y': y}), 'x', 'y') return tf.shade(agg, cmap=colormap) #--------------------------------------------------------------------------------- pn.interact(hopalong1_plot, n=(1, 10000000), colormap=ps) #--------------------------------------------------------------------------------- # The value of this attractor can be changed freely. # Try it in the jupyter notebook.
return view_fn(avg, avg[outliers]) kw = dict(window=(1, 60), variable=sorted(list(data.columns)), sigma=(1, 20)) tap = hv.streams.PointerX(x=data.index.min()) def hvplot2(avg, highlight): line = avg.hvplot(height=300, width=500) outliers = highlight.hvplot.scatter(color="orange", padding=0.1) tap.source = line return (line * outliers).opts(legend_position="top_right") @pn.depends(tap.param.x) def table(x): index = np.abs((data.index - x).astype(int)).argmin() return data.iloc[index] app = pn.interact(find_outliers, view_fn=hvplot2, **kw) row = pn.Row( pn.Column("## Room Occupancy\nHover over the plot for more information.", app[0]), pn.Row(app[1], table), ) row.servable()
select_gene = pn.widgets.Select(name='Select gene', options=list(outdict.keys())) select_growth = pn.widgets.Select(name='Select growth', options=list( outdict[select_gene.value].keys())) def plot_infoshift(gene='aphA', growth='arabinose'): plt.clf() plt.cla() s = outdict[gene][growth] colorinputs = np.zeros((160)) for i in range(160): if s[i] < 0: colorinputs[i] = 0.0 else: colorinputs[i] = 1.0 fig, ax = plt.subplots(figsize=(10, 2)) shiftcolors = plt.cm.bwr(colorinputs) s_abs = np.abs(s) ax.bar(range(160), np.abs(s), color=shiftcolors) #fig = plt.bar(range(160),np.abs(s),color=shiftcolors) plt.close(fig) return fig m = pn.interact(plot_infoshift, gene=select_gene, growth=select_growth) mout = pn.Row(pn.Column(m[0]), pn.Column(m[1])).servable() mout.save('/home/bill/test.html')
def dd_interactive(J1, J2, w): return n_coupling(J1, J2, w=w) def ddd_interactive(J1, J2, J3): return n_coupling(J1, J2, J3) def dddd_interactive(J1, J2, J3, J4): return n_coupling(J1, J2, J3, J4) dd_app = pn.interact(dd_interactive, J1=(0.0, 10.0, 0.1, 3.0), J2=(0.0, 10.0, 0.1, 7.0), w=(0.0, 5.0, 0.1, 0.5) ) ddd_app = pn.interact(ddd_interactive, J1=(0.0, 15.0, 0.1, 4.0), J2=(0.0, 15.0, 0.1, 10.0), J3=(0.0, 15.0, 0.1, 12.0)) dddd_app = pn.interact(dddd_interactive, J1=(0, 20, 0.1, 3.8), J2=(0, 20, 0.1, 6.6), J3=(0, 20, 0.1, 6.6), J4=(0, 20, 0.1, 6.6))
x, y = np.zeros(n), np.zeros(n) x[0], y[0] = x0, y0 for i in np.arange(n - 1): x[i + 1] = np.sin(x[i] * y[i] / b) * y[i] + np.cos(a * x[i] - y[i]) y[i + 1] = np.sin(y[i]) / b + x[i] return x, y #--------------------------------------------------------------------------------- def bedhead_plot(a=1.40, b=1.14, n=1000000, colormap=ps['blues']): cvs = ds.Canvas(plot_width=500, plot_height=500) x, y = bedhead_trajectory(a, b, 1, 1, n) agg = cvs.points(pd.DataFrame({'x': x, 'y': y}), 'x', 'y') return tf.shade(agg, cmap=colormap) #--------------------------------------------------------------------------------- pn.interact(bedhead_plot, n=(1, 10000000), colormap=ps) #--------------------------------------------------------------------------------- # The value of this attractor can be changed freely. # Try it in the jupyter notebook.
} def stock_price(stock): chosen = stocks[stock] return (hv.Curve((chosen['Open'].index, chosen['Open'])) * hv.Curve( (chosen['Close'].index, chosen['Close']))).options( width=700, height=400, legend_position='top_left') # In[ ] stock_logos = { 'goog': Image.open('./data/google_logo.png'), 'aapl': Image.open('./data/apple_logo.png') } def stock_price_with_logo(stock): return pn.Row(pn.panel(stock_logos[stock], height=200), stock_price(stock)) stock_explorer = pn.interact(stock_price_with_logo, stock=['goog', 'aapl']) stock_explorer title = """<span style="font-weight:bold;font-size:x-large">Stock price dashboard</span>""" pn.Column(pn.panel(title, height=10), stock_explorer) dashboard = pn.Column(pn.Row(pn.Spacer(width=350), pn.panel(title, height=10)), stock_explorer) dashboard
for i in np.arange(n - 1): x[i + 1] = a * y[i] * (1 - b * y[i] * y[i]) + y[i] + Gumowski(x[i], mu) y[i + 1] = -x[i] + Gumowski(x[i + 1], mu) return x, y #-------------------------------------------------------------------------------------- def GumowskiMira_plot(a=0.01, b=0.05, mu=-0.8, n=100000, colormap=ps['bgyw']): cvs = ds.Canvas(plot_width=800, plot_height=800) x, y = GumowskiMira_trajectory(a, b, mu, 0, 0.5, n) agg = cvs.points(pd.DataFrame({'x': x, 'y': y}), 'x', 'y') return tf.shade(agg, cmap=colormap) #-------------------------------------------------------------------------------------- pn.interact(GumowskiMira_plot, n=(1, 1000000)) #-------------------------------------------------------------------------------------- # The value of this attractor can be changed freely. # Try it in the jupyter notebook.
return x, y #=================================================================================================== def JasonRampe1_plot(x0=0, y0=0, n=100000, a=2.6, b=-2.6, c=-0.6, d=0.7, cmap=["yellow", "orange"]): cvs = ds.Canvas(plot_width=700, plot_height=700) x, y = JasonRampe1_trajectory(x0, y0, n, a, b, c, d) agg = cvs.points(pd.DataFrame({'x': x, 'y': y}), 'x', 'y') return tf.shade(agg, cmap) #=================================================================================================== pn.extension() pn.interact(JasonRampe1_plot, n=(1, 1000000)) #=================================================================================================== # The value of this attractor can be changed freely. Try it in the jupyter notebook.
return fig def find_outliers(variable='Temperature', window=30, sigma=10, view_fn=mpl_plot): avg = data[variable].rolling(window=window).mean() residual = data[variable] - avg std = residual.rolling(window=window).std() outliers = (np.abs(residual) > std * sigma) return view_fn(avg, avg[outliers]) pn.extension() pn.interact(find_outliers) text = "<br>\n# Room Occupancy\nSelect the variable, and the time window for smoothing" kw = dict(window=(1, 60), variable=sorted(list(data.columns)), sigma=(1, 20)) i = pn.interact(find_outliers, **kw) p = pn.Row(i[1][0], pn.Column(text, i[0][0], i[0][1])) variable = pnw.RadioButtonGroup(name='variable', value='Temperature', options=list(data.columns)) window = pnw.IntSlider(name='window', value=10, start=1, end=60) reactive_outliers = pn.bind(find_outliers, variable, window, 10)