def volplot_2(df1): #Data for volcano plot 2: df1=df1.dropna(how='any') df1 = df1[df1.Fold_change != 0] #remove rows where fold change is 0 df1["Log_Fold_change"]=np.log2(df1["Fold_change"]) df1["Log_p_value"]=-np.log10(df1["p_value"]) #Volcano plot 2: source=ColumnDataSource(df1) vol_hover=HoverTool(tooltips=[('Kinase','@Kinase'), ('Substrate', '@Substrate'), ('Modified Residue','@Phosphosite'), ('Fold Change','@Fold_change'), ('p-value', '@p_value')]) p2 = figure(plot_width=700, plot_height=500) p2.title.text="Volcano Plot of the Log Fold Change and Log p-value for All Identified Kinases" p2.title.text_font_size = "15px" p2.xaxis.axis_label ="Log Fold Change" p2.yaxis.axis_label ="-Log p-value" p2.scatter(x='Log_Fold_change', y='Log_p_value', source=source) p2.add_tools(vol_hover) #Significance thresholds: sig5=Span(location=1.3, dimension='width', line_color='#800000', line_width=1.75, line_dash='dashed') #5% sig1=Span(location=2, dimension='width', line_color='#2F4F4F', line_width=1.75, line_dash='dashed') #1% toggle1=Toggle(label='1% Significance', button_type="success", active=True) toggle1.js_link('active', sig1, 'visible') toggle2=Toggle(label='5% Significance', button_type="success", active=True) toggle2.js_link('active', sig5, 'visible') p2.add_layout(sig1) #adds horizontal line where points below line are non-sig fold changes(-log(0.05)=1.3) p2.add_layout(sig5) plot3=layout([p2], [toggle1, toggle2]) return plot3
def toggle(filter_col, filter): title = re.sub(r'\s*[(]F[0-9]+[)]\s*', '', filter_col) class_select = title.replace(" ", "") title = title.upper() select_toggle = Toggle( label=title, width=175, name=class_select, active=True ) select_toggle.js_link('active', filter, 'visible') return select_toggle
hover = HoverTool(tooltips=[("Ice Temp (C)","@temp_list2"),("Bacterial Population", "$x"),("Viral Population", "$y"), ("Lytic %", "@lytic")]) mapper = LinearColorMapper(palette=viridis(256), low=min(temp_list2), high=max(temp_list2)) p = figure(plot_height=500, plot_width=500, x_axis_type = 'log', y_axis_type = 'log',x_range = (1e4, 1e8), y_range = (1e5,1e10), tools = [hover]) p.xaxis.axis_label = 'Bacteria per mL' p.yaxis.axis_label = 'Virus per mL' # plot the ratio lines Ratiolines = np.linspace(1e4, 1e8,1000) Lines = p.line(Ratiolines, 1*Ratiolines) Lines2 = p.line(Ratiolines, 10*Ratiolines) Lines3 = p.line(Ratiolines, 100*Ratiolines) Lines4 =p.line(Ratiolines, 1000*Ratiolines) Lines5= p.line(Ratiolines, 10000*Ratiolines) toggle2 = Toggle(label="Ratio Lines", button_type="success", active=True) toggle2.js_link('active', Lines , 'visible') toggle2.js_link('active', Lines2 , 'visible') toggle2.js_link('active', Lines3 , 'visible') toggle2.js_link('active', Lines4 , 'visible') toggle2.js_link('active', Lines5 , 'visible') #plot the data p.circle('x', 'y', fill_color= transform('temp_list2', mapper), size = 'size_list', fill_alpha=0.6, line_color=None, source = source) layout = row( p, toggle2 ) show(layout)
right=box_right, line_width=1, line_color="black", line_dash="dashed", fill_alpha=0.2, fill_color="orange", name="Lockdown Introduction", ) fig_london_mob.add_layout(box_london_mob) fig_london_mob.xaxis.major_tick_line_color = "firebrick" fig_london_mob.xaxis.major_tick_line_width = 1 fig_london_mob.xaxis.minor_tick_line_color = "black" toggle_london_mob = Toggle(label="Show National Lockdown", button_type="success", active=True) toggle_london_mob.js_link("active", box_london_mob, "visible") ## Set up the figure for UK mobility fig_uk_mob = figure( title="COVID-19 Mobility Variables for UK", plot_height=550, plot_width=900, x_axis_label="Date", y_axis_label="Change from the baseline in %", x_minor_ticks=2, y_range=(-150, 170), toolbar_location=None, x_axis_type="datetime", ) # Connect to and draw the data for c in df_uk_mobility.iloc[:, 1:]:
from bokeh.io import output_file, show from bokeh.layouts import layout from bokeh.models import BoxAnnotation, Toggle from bokeh.plotting import figure output_file("styling_visible_annotation_with_interaction.html") p = figure(width=600, height=200, tools='') p.line([1, 2, 3], [1, 2, 1], line_color="#0072B2") pink_line = p.line([1, 2, 3], [2, 1, 2], line_color="#CC79A7") green_box = BoxAnnotation(left=1.5, right=2.5, fill_color='#009E73', fill_alpha=0.1) p.add_layout(green_box) # Use js_link to connect button active property to glyph visible property toggle1 = Toggle(label="Green Box", button_type="success", active=True) toggle1.js_link('active', green_box, 'visible') toggle2 = Toggle(label="Pink Line", button_type="success", active=True) toggle2.js_link('active', pink_line, 'visible') show(layout([p], [toggle1, toggle2]))
def showGUI(self, pth_to_img, y_form, pred): ''' Method builds the bokeh GUI Parameters ---------- pth_to_img: path to ultrasound image y_form: true form of the lesion pred: predicted form the lesion ''' ############## #Set up a figure ############## p = figure(x_range=(0, self.DIMS[0]), y_range=(0, self.DIMS[1]), tools=self._tools_to_show, plot_width=self.DIMS[0], plot_height=self.DIMS[1], toolbar_location="above") #Add image as background p.image_url(url=[self.root_pth + pth_to_img], x=431, y=302, w=862, h=604, anchor="center") #Nicier plot self._makeShiny(plot=p) ############## #Add lines and plot them ############## src_true, src_pred = self._getData() self._plotLines(plot=p, src_true=src_true, src_pred=src_pred) ############## #Add table ############## table = self._addTable(src_pred=src_pred) ############## #Add polygons ############## true_pol, c_t = self._addLesionForm(form=y_form, color='red', plot=p) pred_pol, c_p = self._addLesionForm(form=pred, color='blue', plot=p) #Add toggles for polygons toggle_true = Toggle(label="Show true form", button_type="primary", active=True) toggle_true.js_link('active', true_pol, 'visible') toggle_true.js_link('active', c_t, 'visible') toggle_pred = Toggle(label="Show predicted form", button_type="primary", active=True) toggle_pred.js_link('active', pred_pol, 'visible') toggle_true.js_link('active', c_p, 'visible') ############## #Add download button ############## button_csv = Button(label="Download", button_type="primary") button_csv.callback = CustomJS(args=dict(source=src_pred), code=open(self.root_pth + "download.js").read()) ############## #Add title div ############## div_title = Div(text="""<div> <b>LESION ADJUSTER</b> </div>""", align='center', style={ 'font-size': '150%', 'color': '#1f77b4' }) ############## #Add description to the buttons ############## div_desc = Div(text="""<div> <b>CONTROLS</b> </div>""", align='center', style={ 'font-size': '110%', 'color': '#1f77b4' }) ############## #Add Div to show euclidean distance and button to recalculate it ############## div_euclid = Div(text=""" <b>Diameter of predicted form is:</b> 334.80 <br> <b>Diameter of true form is:</b> 368.64 <br> <b>RMSE is:</b> 34.13 """, align='center', style={'font-size': '100%'}) p.js_on_event( events.MouseMove, CustomJS(args=dict(div=div_euclid, source_data_pred=src_pred, source_data_true=src_true), code=""" var data_p = source_data_pred.data; var data_t = source_data_true.data; var x_p = data_p['x'] var y_p = data_p['y'] var x_t = data_t['x'] var y_t = data_t['y'] var diam_p = 0 var diam_t = 0 var rmse = 0 //Diameter of pred form diam_p = Math.sqrt(Math.pow((x_p[0]-x_p[1]),2) + Math.pow((y_p[0]-y_p[1]),2)) //Diameter of true form diam_t = Math.sqrt(Math.pow((x_t[0]-x_t[1]),2) + Math.pow((y_t[0]-y_t[1]),2)) //RMSE rmse = Math.sqrt(Math.pow(diam_p - diam_t,2)/1) //Result div.text = "<b>Diameter of predicted form is: </b>" + diam_p.toFixed(2) + "<br> <b>Diameter of true form is: </b>" + diam_t.toFixed(2) + " <br> <b>RMSE is: </b>" + rmse.toFixed(2); """)) ############## #Show ############## show( Column( div_title, Row( Column(p, table), Column(div_desc, toggle_true, toggle_pred, button_csv, div_euclid))))
class Carte_tronçons(Fond_de_carte): """Carte de tronçons de lignes. Arguments: tronçons: GeoDataFrame, table des tronçons Attributs: tron: table des tronçons avec habillage tron_idx_name: le nom de l'index des tronçons transformé en colonne dans `tron` """ titre_ref = "carte_tronçons" titre_tron = "Tronçons" # coordonnées arbitraires de la carte pour créer des objets de la légende x_legende, y_legende = [277409, 277409], [6248780, 6248780] tab_width = 500 def __init__(self, tronçons: DataFrame, **kwargs) -> None: self.tron = tronçons self.tron["line_width"] = self.line_width self.tron["line_color"] = self.line_color self.tron.reset_index(inplace=True) self.tron_idx_name = self.tron.columns[0] self.cols = self.tron.columns.drop( ["geometry", "line_width", "line_color"], errors="ignore") super().__init__(**kwargs) @property def cols_tron(self) -> list[TableColumn]: return [TableColumn(field=c, title=c) for c in self.cols] @property def line_width(self) -> Series: """Épaisseur de l'affichage des tronçons. Doit renvoyer une série alignable avec l'argument tronçons et peut y faire référence via self.tron. """ return 2 @property def line_color(self) -> Series: """Couleur de l'affichage des tronçons. Doit renvoyer une série alignable avec l'argument tronçons et peut y faire référence via self.tron. """ return "blue" @property def tooltips(self) -> list[tuple[str, str]]: return [(c, f"@{c}") for c in self.cols] @property def texte_aide(self) -> str: return """<b>Mode d'emploi</b> <p>La sélection d'une ou plusieurs lignes est possible directement sur la carte (shift + clic) ou dans la table (shift/ctrl + clic).</p> <p>On peut aussi sélectionner une ligne en indiquant son numéro de ligne et de rang dans l'entrée texte située en haut à droite. Le bouton "Affiche les extrémités" permet de rendre visibles ou non les extrémités des lignes sélectionnées.</p> <p>En cas de problème, utiliser l'outil reset sur la droite de la carte.</p> """ def ajoute_table_tron(self) -> None: view = CDSView(source=self.source_lines, filters=[self.filter]) self.table_tron = DataTable( source=self.source_lines, view=view, columns=self.cols_tron, autosize_mode="none", sizing_mode="stretch_height", width=self.tab_width, height=200, ) def ajoute_toggle_extrémités(self) -> None: size = 4 fill_color = "DarkSlateGray" self.g = (self.tron.set_index( self.tron_idx_name).geometry.boundary.dropna().explode().droplevel( 1).rename("geometry").reset_index().reset_index()) idx_g = self.g.columns[0] # colonne qui contient le numéro de ligne self.src_extr = GeoJSONDataSource(geojson=self.g.to_json()) self.filter_extr = IndexFilter(list(range(self.g.shape[0]))) self.index_extrémités_par_tron = ( self.tron.reset_index() # numéro de ligne dans la colonne idx_g .merge( self.g, on=self.tron_idx_name ) # inner join donc tous les tronçons non localisés n'y sont pas .groupby(f"{idx_g}_x").apply( lambda s: list(s[f"{idx_g}_y"])).to_dict()) view = CDSView(source=self.src_extr, filters=[self.filter_extr]) self.extr_renderer = self.p.circle( x="x", y="y", size=size, fill_color=fill_color, line_color=fill_color, source=self.src_extr, visible=False, view=view, ) self.toggle_extr = Toggle(label="Affiche les extrémités", button_type="success", width=100) self.toggle_extr.js_link("active", self.extr_renderer, "visible") def ajoute_lignes(self) -> None: self.p.multi_line( xs="xs", ys="ys", line_color="line_color", line_width="line_width", source=self.source_lines, name="tronçons", ) @property def callback_selected(self) -> CustomJS: return CustomJS( args=dict( src_lines=self.source_lines, src_extr=self.src_extr, filter=self.filter, filter_extr=self.filter_extr, index_extr_dict=self.index_extrémités_par_tron, ), code="""var sel = src_lines.selected.indices; if (sel.length == 0) { sel = [...Array(src_lines.length).keys()]; var sel2 = [...Array(src_extr.length).keys()]; } else { var sel2 = sel.flatMap(el => index_extr_dict[el]); } filter.indices = sel; filter_extr.indices = sel2; src_lines.change.emit(); src_extr.change.emit(); """, ) def ajoute_input_num(self, title: str = None, groupby: str = None, max_width=80) -> None: """Sélection du tronçon par une colonne de la table.""" if groupby is None: groupby = self.tron_idx_name if title is None: title = self.tron_idx_name index_par_tron = DataFrame(self.tron).groupby(groupby).apply( lambda s: list(s.index)).to_dict() self.input_num = TextInput(value="", title=title, max_width=max_width) callback_text = CustomJS( args=dict( text=self.input_num, src_lines=self.source_lines, index_par_tron=index_par_tron, ), code="""if (text.value in index_par_tron) { src_lines.selected.indices = index_par_tron[text.value] src_lines.change.emit(); } """, ) self.input_num.js_on_change("value", callback_text) def ajoute_légende(self) -> None: pass @property def titre_tron_div(self) -> Div: return Div(text=f"<b>{self.titre_tron}</b>") def init_layout(self) -> None: super().init_layout() geojson = self.tron.to_json().replace( "null", '{"type":"Point","coordinates":[]}') self.source_lines = GeoJSONDataSource(geojson=geojson) self.filter = IndexFilter(list(range(self.tron.shape[0]))) self.ajoute_lignes() self.ajoute_toggle_extrémités() self.source_lines.selected.js_on_change("indices", self.callback_selected) self.ajoute_table_tron() self.ajoute_input_num() self.hover_tool = self.p.select(type=HoverTool) self.hover_tool.names = ["tronçons"] self.ajoute_légende() self.première_ligne = row(self.input_num, self.toggle_extr) def cstr_layout(self) -> Box: return row( self.p, column( self.première_ligne, self.titre_tron_div, self.table_tron, self.questions, self.aide, ), )
#Redimensionnement des tableaux Xi = np.array(xi).reshape(-1, 1) Yi = np.array(yi).reshape(-1, 1) # Création du model de regression linéaire regression = linear_model.LinearRegression() #Entrainement du model sur les données Xi et Yi regression.fit(Xi, Yi) #Utilisation du model pour une prédiction sur les données Xi pred = regression.predict(Xi) #Nuage de points et droite de regression linéaire nuage = figure( plot_width=500, plot_height=300, title="Droite de regression linéaire et corrélation entre Xi et Yi") nuage.xaxis.axis_label = "Xi" nuage.yaxis.axis_label = "Yi" nuage.scatter(xi, yi, size=10, color="blue") droite = nuage.line(xi, pred.flatten(), line_color="#FC0A05") #Bouton bouton = Toggle(label="Masquer / Afficher la droite de regression linéaire", button_type="success", active=True) bouton.js_link("active", droite, "visible") show(layout([nuage], [bouton]))
def JSandDivDoublePlotWithToggle(x_axis, y_axisRaw, y_axisBin, change_points=[], title="", TOOLTIPS=[], transList=[], alarmList=[], abnormalList=[]): if TOOLTIPS: plot = figure(tooltips=TOOLTIPS, title=title, x_axis_label='Timestamp', y_axis_label='Flux', sizing_mode="stretch_both") else: TOOLTIPS = [ ("index", "$index"), ("(x,y)", "(@x{0,0}, @y{0,0.000}"), ] plot = figure(tooltips=TOOLTIPS, title=title, x_axis_label='Timestamp', y_axis_label='Flux', sizing_mode="stretch_both") rawSource = ColumnDataSource(data=dict(x=x_axis, y=y_axisRaw)) rawLine = plot.line('x', 'y', source=rawSource, line_alpha=0.4, color='black', line_width=2, legend_label="Raw") rawCircle = plot.circle(x_axis, y_axisRaw, color="black", fill_alpha=0.4, legend_label="Raw", size=2) toggle1 = Toggle(label="Raw Data", button_type="success", active=True) toggle1.js_link('active', rawLine, 'visible') toggle1.js_link('active', rawCircle, 'visible') binSource = ColumnDataSource(data=dict(x=x_axis, y=y_axisBin)) binLine = plot.line('x', 'y', source=binSource, color='red', line_width=4, legend_label="DyBin") toggle2 = Toggle(label="Dynamic bin", button_type="success", active=True) toggle2.js_link('active', binLine, 'visible') if change_points: for change_point in change_points: change_point_span = Span(location=float(change_point), dimension='height', line_color='#009E73', line_dash='dashed', line_width=1) plot.add_layout(change_point_span) toggle3 = Toggle(label="AnswerTran", button_type="success", active=True) if transList: for trans in transList: start_point = int(trans[0]) end_point = int(trans[1]) tran_box = BoxAnnotation(left=x_axis[start_point], right=x_axis[end_point], fill_alpha=0.2, fill_color="#F0E442") L_span = Span(location=x_axis[start_point], dimension='height', line_color='#a2ff00', line_dash='4 4', line_width=2) R_span = Span(location=x_axis[end_point], dimension='height', line_color='#a2ff00', line_dash='4 4', line_width=2) plot.add_layout(tran_box) plot.add_layout(L_span) plot.add_layout(R_span) toggle3.js_link('active', tran_box, 'visible') toggle3.js_link('active', L_span, 'visible') toggle3.js_link('active', R_span, 'visible') toggle4 = Toggle(label="Alarm", button_type="success", active=True) if alarmList: for alarm in alarmList: # alarm : start,end,alarm start_point = int(alarm['start']) end_point = int(alarm['end']) alarm_point = int(alarm['alarm']) alarm_box = BoxAnnotation(left=x_axis[start_point], right=x_axis[end_point], fill_alpha=0.2, fill_color="#F0E442") alarm_span = Span(location=x_axis[alarm_point], dimension='height', line_color='#a2ff00', line_dash='4 4', line_width=2) plot.add_layout(alarm_box) plot.add_layout(alarm_span) toggle4.js_link('active', alarm_box, 'visible') toggle4.js_link('active', alarm_span, 'visible') toggle5 = Toggle(label="F-test", button_type="success", active=True) if abnormalList: for abnormal in abnormalList: start_point = int(abnormal[0]) end_point = int(abnormal[1]) abnormal_box = BoxAnnotation(left=x_axis[start_point], right=x_axis[end_point], fill_alpha=0.2, fill_color="#F0E442") L_abnormal_span = Span(location=x_axis[start_point], dimension='height', line_color='#a2ff00', line_dash='4 4', line_width=2) R_abnormal_span = Span(location=x_axis[end_point], dimension='height', line_color='#a2ff00', line_dash='4 4', line_width=2) plot.add_layout(abnormal_box) plot.add_layout(L_abnormal_span) plot.add_layout(R_abnormal_span) toggle5.js_link('active', abnormal_box, 'visible') toggle5.js_link('active', L_abnormal_span, 'visible') toggle5.js_link('active', R_abnormal_span, 'visible') plot.legend.border_line_width = 3 plot.legend.click_policy = "hide" plot.legend.border_line_color = "navy" plot.legend.border_line_alpha = 0. plot.xaxis.axis_label_text_font_size = "16pt" plot.xaxis.major_label_text_font_size = "13pt" plot.yaxis.axis_label_text_font_size = "16pt" plot.yaxis.major_label_text_font_size = "13pt" drawSource = ColumnDataSource(data=dict(x=[], y=[])) r = plot.multi_line('xs', 'ys', source=drawSource) tool = FreehandDrawTool(renderers=[r]) plot.add_tools(tool) js, div = components( layout([plot], row(toggle1, toggle2, toggle3, toggle4, toggle5, sizing_mode='scale_width'), sizing_mode="stretch_both")) return js, div
# linear regression object regr = linear_model.LinearRegression() # fit linear model regr.fit(X, Y) # make predictions pred = regr.predict(X) # plot with regression line regr_plot = figure(plot_width=500, plot_height=300) regr_plot.scatter(x, y, size=10) regr_line = regr_plot.line(x, pred.flatten(), line_color='red') toggle_button = Toggle(label='line of best fit', button_type='success', active=True) toggle_button.js_link('active', regr_line, 'visible') show(layout([regr_plot], [toggle_button])) Loading BokehJS ... In [87]: # slider.js_link? Interactive Widgets with ipywidgets In [88]: seattle_weather['year'] = pd.DatetimeIndex(seattle_weather['date']).year seattle_weather.tail() Out[88]: date precipitation temp_max temp_min wind weather year 1456 2015-12-27 8.6 4.4 1.7 2.9 fog 2015 1457 2015-12-28 1.5 5.0 1.7 1.3 fog 2015 1458 2015-12-29 0.0 7.2 0.6 2.6 fog 2015 1459 2015-12-30 0.0 5.6 -1.0 3.4 sun 2015
line_color=mapper_WFH, color=mapper_WFH, alpha=0.5, source=source ) Graph_COVIDlog = p_WFH.line( x='conf1_date', y='conf1_num', color='#FC4F4F', alpha=0.5, source=source1 ) toggle1 = Toggle(label="코로나 상황", button_type="warning", active=True) toggle1.js_link('active', Graph_COVIDlog, 'visible') # ================== Work From Home finish ========================== # ==================== Restaurant =================================== Restaurant_month = ['Jan', 'Feb', 'Mar', 'Apr', 'May'] Restaurant_sales = [13.2, 12.3, 11.3, 13.4, 16.2, 14.2] p_Restaurant = figure( x_range=Restaurant_month, max_width=500, plot_height=250, toolbar_location=None, tools='' )
from bokeh.io import output_file, show from bokeh.plotting import figure from bokeh.layouts import layout from bokeh.models import Toggle, BoxAnnotation output_file("styling_visible_annotation_with_interaction.html") p = figure(plot_width=600, plot_height=200, tools='') p.line([1, 2, 3], [1, 2, 1], line_color="blue") pink_line = p.line([1, 2, 3], [2, 1, 2], line_color="pink") green_box = BoxAnnotation(left=1.5, right=2.5, fill_color='green', fill_alpha=0.1) p.add_layout(green_box) # Use js_link to connect button active property to glyph visble property toggle1 = Toggle(label="Green Box", button_type="success", active=True) toggle1.js_link('active', green_box, 'visible') toggle2 = Toggle(label="Pink Line", button_type="success", active=True) toggle2.js_link('active', pink_line, 'visible') show(layout([p], [toggle1, toggle2]))