output_file("arrow_heads.html") ARROW_HEADS = [TeeHead, OpenHead, NormalHead, VeeHead] HEIGHT = 35 * len(ARROW_HEADS) p = Plot(width=150, height=HEIGHT, x_range=Range1d(0, 1), y_range=Range1d(-0.5, len(ARROW_HEADS) - 0.5), toolbar_location=None, outline_line_color=None, min_border_left=0, min_border_right=0, min_border_top=0, min_border_bottom=0) for i, style in enumerate(ARROW_HEADS): p.add_layout(Arrow(x_start=0.2, y_start=i, x_end=0.2, y_end=i, end=style())) p.add_layout( Label(x=0.2, x_offset=20, y=i, text=style.__name__, text_baseline='middle', text_align='left')) show(p)
def test4(): from bokeh.io import output_file, show from bokeh.plotting import figure req = HistoryRequest(exchange=Exchange.SMART, symbol="goog", interval=Interval.MINUTE, start=datetime.datetime(2019, 8, 3, 9), end=datetime.datetime(2019, 8, 10, 4)) bar_data = rq.rqdata_client.query_history(req) # bar_data = bar_data[-200:] tb = TestBar() date = [] for i, v in enumerate(bar_data): tb.am.update_bar(v) date.append(i) dt = tb.am.time_array close = tb.am.close_array #Create the time series plot plot = figure(plot_width=1800, plot_height=900, x_axis_label='date', y_axis_label='High Prices') plot.line(x=date, y=close) source = ColumnDataSource( data=dict(height=[66, 71, 72, 68, 58, 62], weight=[165, 189, 220, 141, 260, 174], names=['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan'])) labels = LabelSet(x='weight', y='height', text='names', level='glyph', x_offset=5, y_offset=5, source=source, render_mode='canvas') citation = Label(x=70, y=70, x_units='screen', y_units='screen', text='Collected by Luke C. 2016-04-01', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) plot.add_layout(labels) plot.add_layout(citation) plot.triangle(x=100, y=1200) html = file_html(plot, CDN, "my plot") print(html) #Output the plot # output_file('pandas_time.html') show(plot)
def content(): if 'flink' in session: flink = session['flink'] ftype = session['ftype'] # baseline baseline = session['baseline'] pilih_baseline = int(baseline) if (ftype == 'sp2') or (ftype == 'sp28'): sampel1 = session['sampel1'] konsen1 = session['konsen1'] sampel2 = session['sampel2'] konsen2 = session['konsen2'] sampel3 = session['sampel3'] konsen3 = session['konsen3'] sampel4 = session['sampel4'] konsen4 = session['konsen4'] a_file = urllib.request.urlopen(flink) list_of_lists = [] for line in a_file: stripped_line = line.strip() line_list = stripped_line.split() list_of_lists.append(line_list) a_file.close() data = pd.DataFrame(list_of_lists) data.columns = ["time", "ch1", "ch2", "subsidiary", "difference"] data_numpy = data.to_numpy().transpose() data_y = data_numpy[1][0:len(data_numpy[1])] data_y = np.asfarray(data_y, float) data_x = data_numpy[0][0:len(data_numpy[0])] data_x = np.asfarray(data_x, float) # menghilangkan outliers dspk_y = despike(data_y, 50) # moving average filter ma_y = ma(dspk_y, 9) # savitzky-golay filter svg_y = savgol_filter(ma_y, window_length=41, polyorder=2) # change points detection chgpts_y = rpt.Pelt(model='l2').fit(svg_y) result_y = chgpts_y.predict(pen=5000) if pilih_baseline == 1: base_y = baseline_poly_manual(data_x, svg_y) elif pilih_baseline == 2: base_y = baseline_prediction(data_x, svg_y, result_y) #mean mean_sampel = [] dx = 10 j = 0 + dx for i in range(0, len(result_y)): temp = sum(svg_y[j:result_y[i] - dx]) / len( svg_y[j:result_y[i] - dx]) mean_sampel.append(temp) j = result_y[i] + dx #mean sampel sampel = [] for l in range(1, len(result_y)): if (mean_sampel[l - 1] < mean_sampel[l]): temp = mean_sampel[l] sampel.append(temp) #lokasi sample a = 1 lokasi_sample = [] for p in range(1, len(mean_sampel)): if mean_sampel[p - 1] < mean_sampel[p]: t_in = data_x[result_y[p - 1]] t_out = data_x[result_y[p]] lokasi_sample.append(str(t_in) + ";" + str(t_out)) a += 1 #Input Jenis Pengujian dan Konsentrasi Analit jenis, konsentrasi = input_sample(sampel1, konsen1, sampel2, konsen2, sampel3, konsen3, sampel4, konsen4) df = output(data_x, svg_y, lokasi_sample, jenis, konsentrasi) x = df['A'] y = df['B'] elif ftype == 'csv': df = pd.read_csv(flink, usecols=[0, 1, 2, 3, 4], names=['A', 'B', 'C', 'D', 'E']) x = df['A'] y = df['B'] data_numpy = df.to_numpy().transpose() data_y = data_numpy[1][0:len(data_numpy[1])] data_y = np.asfarray(data_y, float) data_x = data_numpy[0][0:len(data_numpy[0])] data_x = np.asfarray(data_x, float) # change points detection chgpts_y = rpt.Pelt(model='l2').fit(data_y) result_y = chgpts_y.predict(pen=5000) if pilih_baseline == 1: base_y = baseline_poly_manual(data_x, data_y) elif pilih_baseline == 2: base_y = baseline_prediction(data_x, data_y, result_y) elif (ftype == 'xlsx') or (ftype == 'xls'): df = pd.read_excel(flink, usecols=[0, 1, 2, 3, 4], names=['A', 'B', 'C', 'D', 'E']) x = df['A'] y = df['B'] data_numpy = df.to_numpy().transpose() data_y = data_numpy[1][0:len(data_numpy[1])] data_y = np.asfarray(data_y, float) data_x = data_numpy[0][0:len(data_numpy[0])] data_x = np.asfarray(data_x, float) # change points detection chgpts_y = rpt.Pelt(model='l2').fit(data_y) result_y = chgpts_y.predict(pen=5000) if pilih_baseline == 1: base_y = baseline_poly_manual(data_x, data_y) elif pilih_baseline == 2: base_y = baseline_prediction(data_x, data_y, result_y) # Get sample concentration by splitting the 'konsentrasi' column def concentration_label(konsen, i): for column in df[[konsen]]: columnSeriesObj = df[column] temp = columnSeriesObj.values[i].split(";", 2) return temp[0] #Add Tooltips: TOOLTIPS = [ ("Index", "$index"), ("Time (s)", "$x"), ("Refractive Unit (RU)", "$y"), ] #Add plot p = figure(title="Data SPR Hasil Algoritma [Normalized]", x_axis_label="Time (s)", y_axis_label="Refractive Unit (RU)", tooltips=TOOLTIPS, toolbar_location="above", tools="pan, hover, box_zoom, reset, wheel_zoom") #Render glyph #Put the legend outside of the plot legend = Legend(items=[ ("Channel 1", [p.line(x, y, line_width=3, muted_alpha=0.2)]), ("Baseline", [p.line(x, base_y, line_width=2, muted_alpha=0.2, color='red')]) ], location="center") p.add_layout(legend, 'right') p.legend.click_policy = "mute" # Customize the plot p.background_fill_color = "beige" p.toolbar.logo = None # Setting bands and labels to distinguish each response for column in df[['C']]: columnSeriesObj = df[column] for i in range(0, columnSeriesObj.count()): temp = [] temp = str(columnSeriesObj.values[i]).split(";", 2) # Add red band between t_in and t_out specified in csv file red_box = BoxAnnotation(left=float(temp[0]), right=float(temp[1]), fill_color='red', fill_alpha=0.2) p.add_layout(red_box) # Add label for each red band mark = Label( x=float(temp[0]), y=(df.loc[df.loc[df['A'] == float(temp[0])].index[0], "B"]), text=df['D'].values[i] + ' ' + concentration_label('E', i) + ' ng/mL', text_font_size='8pt', render_mode='canvas', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) p.add_layout(mark) #Reflectivity average between each response jumlah = 0 count = 0 for j in range( df.loc[df['A'] == float(temp[0])].index[0], 1 + (df.loc[df['A'] == float(temp[1])].index[0])): jumlah += y.values[j] count += 1 avg = round(jumlah / count) #Find the maximum value of RU for each response ru_max = df.loc[(df.loc[df['A'] == float(temp[0])].index[0]):( 1 + (df.loc[df['A'] == float(temp[1])].index[0])), 'B'].max() avg_mark = Label(x=float(temp[0]), y=ru_max, text='RU avg = ' + str(avg), text_font_size='8pt', render_mode='canvas', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) p.add_layout(avg_mark) #Menyematkan grafik ke file HTML script, div = components(p) kwargs = {'script': script, 'div': div} kwargs['title'] = 'bokeh-with-flask' data = session['data'] return render_template('content.html', **kwargs, data=data) else: return render_template('index.html')
def create_prediction_plot(df, current_date): """Crea gráfica de predicción a futuro. Parameters: df (Dataframe): Dataframe con los datos a mostrar en la visualización. current_date: Ultima fecha antes de la prediccion Returns: Figure: Gráfica de de predicción a futuro. """ hover_tool = HoverTool(tooltips=[('Fecha', '$x{%b %Y}'), ('Predicción', '@Prediction')], formatters={ '$x': 'datetime', }, mode='mouse') # Estructuración de los tipos de datos del dataframe df['añomes'] = pd.to_datetime(df['añomes'], format='%m/%d/%y %I:%M %p') df['Prediction'] = pd.to_numeric(pd.Series(df['Prediction'].values)) prediction_plot = figure(plot_height=400, toolbar_location=None, sizing_mode='stretch_width', x_axis_type='datetime', output_backend="webgl") source_cluster_0 = create_data_source_from_dataframe( df, 'cluster', 'cluster_0') source_cluster_1 = create_data_source_from_dataframe( df, 'cluster', 'cluster_1') source_cluster_2 = create_data_source_from_dataframe( df, 'cluster', 'cluster_2') source_cluster_3 = create_data_source_from_dataframe( df, 'cluster', 'cluster_3') x_axis_tick_vals = source_cluster_0.data['añomes'].astype(int) / 10**6 prediction_plot.line(x='añomes', y='Prediction', source=source_cluster_0, line_width=2, line_color=bokeh_utils.LINE_COLORS_PALETTE[0], legend_label='Cluster 0') prediction_plot.line(x='añomes', y='Prediction', source=source_cluster_1, line_width=2, line_color=bokeh_utils.LINE_COLORS_PALETTE[1], legend_label='Cluster 1') prediction_plot.line(x='añomes', y='Prediction', source=source_cluster_2, line_width=2, line_color=bokeh_utils.LINE_COLORS_PALETTE[2], legend_label='Cluster 2') prediction_plot.line(x='añomes', y='Prediction', source=source_cluster_3, line_width=2, line_color=bokeh_utils.LINE_COLORS_PALETTE[3], legend_label='Cluster 3') prediction_plot.xaxis.major_label_orientation = np.pi / 4 prediction_plot.xaxis.major_label_text_color = bokeh_utils.LABEL_FONT_COLOR prediction_plot.yaxis.major_label_text_color = bokeh_utils.LABEL_FONT_COLOR prediction_plot.legend.location = 'top_left' prediction_plot.legend.orientation = 'horizontal' prediction_plot.legend.click_policy = 'hide' prediction_plot.legend.label_text_color = bokeh_utils.LABEL_FONT_COLOR prediction_plot.xaxis[0].formatter = DatetimeTickFormatter( months=['%b %Y']) prediction_plot.xaxis[0].ticker = FixedTicker(ticks=list(x_axis_tick_vals)) # Linea vertical para definir el horizonte de predicción # current_date = dt.now() - timedelta(days=1) prediction_date = time.mktime(current_date.timetuple()) * 1000 vline = Span(location=prediction_date, dimension='height', line_color='gray', line_alpha=0.6, line_dash='dotted', line_width=2) prediction_plot.add_layout(vline) # Etiqueta linea horizontal vlabel = Label(x=prediction_date, y=25, text='→Predicción', text_color='gray', text_alpha=0.6, text_font_size='14px') prediction_plot.add_layout(vlabel) prediction_plot.title.text = 'Predicción de los clusters a futuro' prediction_plot.title.text_color = bokeh_utils.TITLE_FONT_COLOR prediction_plot.title.align = 'left' prediction_plot.title.text_font_size = '16px' prediction_plot.border_fill_color = bokeh_utils.BACKGROUND_COLOR prediction_plot.add_tools(hover_tool) prediction_plot.min_border_right = 15 return prediction_plot
level="overlay") plot.text(x="MetersBack", y="Year", x_offset=10, y_offset=-5, text="SelectedName", text_align="left", text_baseline="middle", text_font_size="12px", source=source) no_olympics_label = Label(x=7.5, y=1942, text="No Olympics in 1940 or 1944", text_align="center", text_baseline="middle", text_font_size="12px", text_font_style="italic", text_color="silver") no_olympics = plot.add_layout(no_olympics_label) x = sprint[sprint.Year == 1900].MetersBack.min() - 0.5 arrow = Arrow(x_start=x, x_end=5, y_start=1900, y_end=1900, start=NormalHead(fill_color="black", size=6), end=None, line_width=1.5) plot.add_layout(arrow)
def test_plot_add_layout_adds_label_to_plot_renderers(): plot = figure() label = Label() plot.add_layout(label) assert label in plot.center
plot.line('x', 'y', source=line_source, line_width=3, line_alpha=0.6, color='black') plot.circle('x', 'y', source=point_source, size=10, color='black') # set up static line and annotations plot.line(x_line, y_line, line_width=5, color='blue', line_alpha=0.3) plot.circle(x_points, y_points, size=10, color='blue', line_alpha=0.3) mytext = Label(x=-7, y=105, text='pIC50 = 6, Hill Coefficient = 1', text_color="blue", text_alpha=0.5) plot.add_layout(mytext) # add axes lines vline = Span(location=0, dimension='height', line_color='black', line_width=1, line_alpha=0.3) hline = Span(location=0, dimension='width', line_color='black', line_width=1, line_alpha=0.3)
tooltips="@KB_Article: @Percentage{0.0}%") p.wedge(x=0, y=1, radius=1.2, name='Percentage', start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', legend="KB_Article", source=df) p.axis.axis_label = None p.axis.visible = False p.grid.grid_line_color = None p.legend.label_text_font_size = "12pt" p.add_layout(Label(x=0, y=1.4, text='38.1%')) p.add_layout(Label(x=-.9, y=.9, text='31.7%')) p.add_layout(Label(x=-.15, y=.4, text='10.1%')) p.add_layout(Label(x=.75, y=.86, text='5.3%')) p.add_layout(Label(x=.4, y=.19, text='3.4%')) p.add_layout(Label(x=.7, y=.27, text='3.0%')) p.add_layout(Label(x=.87, y=.4, text='2.2%')) p.add_layout(Label(x=.97, y=.48, text='2.2%')) p.add_layout(Label(x=1.02, y=.565, text='2.1%')) p.add_layout(Label(x=1, y=.67, text='1.9%')) show(p) #%% """ Create data visualization on a monthly basis This will be the new data
def display_timeline(data, alert=None, overlay_data=None, title: str = None, time_column: str = 'TimeGenerated', source_columns: list = None, overlay_colums: list = None, height: int = 300): """ Display a timeline of events. Arguments: data {pd.DataFrame} -- Input DataFrame Keyword Arguments: alert {SecurityAlert} -- Input alert (optional) (default: {None}) overlay_data {pd.DataFrame} -- Second event stream (DataFrame) to display as overlay (default: {None}) title {str} -- [description] (default: {None}) time_column {str} -- The name of the time property used in the Dataframe(s) (default: {'TimeGenerated'}) source_columns {list} -- List of source columns to use in tooltips (default: {None}) overlay_colums {list} -- List of source columns to use in overlay data tooltips (default: {None}) heigh {int} -- the height of the plot figure (under 300 limits access to Bokeh tools) """ reset_output() output_notebook() # pylint: disable=C0103 WRAP = 50 WRAP_CMDL = 'WrapCmdl' # pylint: enable=C0103 y_max = 1 if not source_columns: source_columns = ['NewProcessName', 'EventID', 'CommandLine'] if time_column not in source_columns: source_columns.append(time_column) if 'CommandLine' in source_columns: graph_df = data[source_columns].copy() graph_df[WRAP_CMDL] = graph_df.apply( lambda x: _wrap_text(x.CommandLine, WRAP), axis=1) else: graph_df = data[source_columns].copy() # if we have an overlay - add this data and shift the y co-ordinates to # show on two separate lines if overlay_data is not None: overlay_colums = (overlay_colums if overlay_colums is not None else source_columns) if time_column not in overlay_colums: overlay_colums.append(time_column) if 'CommandLine' in overlay_colums: overlay_df = overlay_data[overlay_colums].copy() overlay_df[WRAP_CMDL] = overlay_df.apply( lambda x: _wrap_text(x.CommandLine, WRAP), axis=1) else: overlay_df = overlay_data[overlay_colums].copy() graph_df['y_index'] = 2 overlay_df['y_index'] = 1 y_max = 2 else: graph_df['y_index'] = 1 source = ColumnDataSource(graph_df) # build the tool tips from columns (excluding these) excl_cols = [time_column, 'CommandLine'] tool_tip_items = [(f'{col}', f'@{col}') for col in source_columns if col not in excl_cols] if WRAP_CMDL in graph_df: tool_tip_items.append(('CommandLine', f'@{WRAP_CMDL}')) hover = HoverTool( tooltips=tool_tip_items, formatters={'Tooltip': 'printf'} # display a tooltip whenever the cursor is vertically in line with a glyph # ,mode='vline' ) if not title: title = 'Event Timeline' else: title = 'Timeline {}'.format(title) # tools = 'pan, box_zoom, wheel_zoom, reset, undo, redo, save, hover' plot = figure(min_border_left=50, plot_height=height, plot_width=900, x_axis_label='Event Time', x_axis_type='datetime', x_minor_ticks=10, tools=[hover, 'pan', 'xwheel_zoom', 'box_zoom', 'reset'], title=title) plot.yaxis.visible = False # Tick formatting for different zoom levels # '%H:%M:%S.%3Nms tick_format = DatetimeTickFormatter() tick_format.days = ['%m-%d %H:%M'] tick_format.hours = ['%H:%M:%S'] tick_format.minutes = ['%H:%M:%S'] tick_format.seconds = ['%H:%M:%S'] tick_format.milliseconds = ['%H:%M:%S.%3N'] plot.xaxis[0].formatter = tick_format plot.circle(x=time_column, y='y_index', color='navy', alpha=0.5, size=10, source=source) if overlay_data is not None: overlay_source = ColumnDataSource(overlay_df) plot.circle(x=time_column, y='y_index', color='green', alpha=0.5, size=10, source=overlay_source) # Adding data labels stops everything working! # labels = LabelSet(x=time_column, y='y_index', y_offset=5, # text='NewProcessName', source=source, # angle='90deg', text_font_size='8pt') # p.add_layout(labels) # if we have an alert, plot the time as a line if alert is not None: x_alert_label = pd.Timestamp(alert['StartTimeUtc']) plot.line(x=[x_alert_label, x_alert_label], y=[0, y_max + 1]) alert_label = Label(x=x_alert_label, y=0, y_offset=10, x_units='data', y_units='data', text='< Alert time', render_mode='css', border_line_color='red', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) plot.add_layout(alert_label) print('Alert start time = ', alert['StartTimeUtc']) show(plot)
label_opts2 = dict(x=-84, y=47, x_units='screen', y_units='screen') label_opts3 = dict(x=612, y=64, x_units='screen', y_units='screen', text_align='right', text_font_size='9pt') msg1 = 'By Exoplots' # when did the data last get updated modtimestr = get_update_time().strftime('%Y %b %d') msg3 = 'Data: NASA Exoplanet Archive' caption1 = Label(text=msg1, **label_opts1) caption2 = Label(text=modtimestr, **label_opts2) caption3 = Label(text=msg3, **label_opts3) fig.add_layout(caption1, 'below') fig.add_layout(caption2, 'below') fig.add_layout(caption3, 'below') plotting.save(fig) # save the individual pieces so we can just embed the figure without the whole # html page script, div = components(fig) with open(embedfile, 'w') as ff: ff.write(div) ff.write(script)
def test_plot_add_layout_raises_error_if_plot_already_on_annotation(): plot = figure() with pytest.raises(ValueError): plot.add_layout(Label(plot=plot))
legend_label='Expected', line_width=1) covid_line = p.line(x='index', y='expected_plus_covid', source=merged_df, name='COVID-19 Deaths', color='red', legend_label='COVID-19', line_width=1) # create and add bands confidence_interval = Band(base='index', lower='defunciones_esperadas_q99', upper='defunciones_esperadas_q01', source=ColumnDataSource(merged_df), level='underlay', fill_alpha=1.0, line_width=1, line_color='black') p.add_layout(confidence_interval) # create lockdown span lockdown_date = time.mktime(dt(2020, 3, 14, 0, 0, 0).timetuple()) * 1000 lockdown_start = Span(location=lockdown_date, dimension='height', line_color=palette[3], line_dash='dashed', line_width=2) lockdown_label = Label(x=lockdown_date, y=10, y_units='screen', text=' Lockdown', text_font='helvetica', text_font_size='9pt') # create phase 0 span phase0_date = time.mktime(dt(2020, 5, 2, 0, 0, 0).timetuple()) * 1000 phase0_start = Span(location=phase0_date, dimension='height', line_color=palette[6], line_dash='dashed', line_width=2) phase0_label = Label(x=phase0_date, y=10, y_units='screen', text=' 0', text_font='helvetica', text_font_size='9pt') # create phase 1 span phase1_date = time.mktime(dt(2020, 5, 11, 0, 0, 0).timetuple()) * 1000 phase1_start = Span(location=phase1_date, dimension='height', line_color=palette[7], line_dash='dashed', line_width=2) phase1_label = Label(x=phase1_date, y=10, y_units='screen', text=' 1', text_font='helvetica', text_font_size='9pt')
def test_Label_accepts_datetime_xy(): obj = Label(x=datetime(2018, 8, 7, 0, 0), y=datetime(2018, 8, 7, 0, 0)) assert obj.x == 1533600000000.0 assert obj.y == 1533600000000.0
regions_df.rename({'Group':'region'}, axis='columns', inplace=True) for year in years: df_year = df.iloc[:,df.columns.get_level_values(1)==year] df_year.columns = df_year.columns.droplevel(1) data[year] = df_year.join(regions_df.region).reset_index().to_dict('series') source = ColumnDataSource(data=data[years[0]]) plot = figure(x_range=(1, 9), y_range=(20, 100), title='Gapminder Data', height=300) plot.xaxis.ticker = SingleIntervalTicker(interval=1) plot.xaxis.axis_label = "Children per woman (total fertility)" plot.yaxis.ticker = SingleIntervalTicker(interval=20) plot.yaxis.axis_label = "Life expectancy at birth (years)" label = Label(x=1.1, y=18, text=str(years[0]), text_font_size='93px', text_color='#eeeeee') plot.add_layout(label) color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list) plot.circle( x='fertility', y='life', size='population', source=source, fill_color={'field': 'region', 'transform': color_mapper}, fill_alpha=0.8, line_color='#7c7e71', line_width=0.5, line_alpha=0.5, legend_group='region', )
def plot_iv(doc): init_calc = iv.iv_data(72, 800, 25, 45.9, 9.25, 37.2, 8.76, 7.47, 100) source = ColumnDataSource(data=init_calc[0]) source_translated = ColumnDataSource(data=init_calc[1]) res_source = ColumnDataSource(data=init_calc[2]) status_param = init_calc[3] print(status_param) plot = Figure(plot_width=600, plot_height=600, y_range=(-1, 10), x_range=(0, 60)) plot.xaxis.axis_label = 'Voltage (V)' plot.yaxis.axis_label = 'Current (I)' plot.scatter( 'x', 'y', source=source, line_width=3, line_alpha=0.6, ) plot.scatter( 'x', 'y', source=source_translated, line_width=3, line_alpha=0.6, line_color='red', ) sig_plot = Figure(plot_width=300, plot_height=300, x_axis_label='Series Resistance (Rs)', y_axis_label='Shunt Resistance (Rsh)', title='Calculated Resistances') sig_plot.scatter('x', 'y', source=res_source, line_width=10) vline = Span(location=0, dimension='height', line_color='red', line_width=3) # Horizontal line hline = Span(location=0, dimension='width', line_color='green', line_width=3) sig_plot.renderers.extend([vline, hline]) error_plt = Figure( plot_width=100, plot_height=50, toolbar_location=None, ) if (status_param.success == True): print('Successful Entry to the landing page') cite = Label(text='Success', render_mode='css', text_color='white', border_line_color='green', background_fill_color='green') else: print('Inside fail') cite = Label(text='False', render_mode='css', text_color='white', border_line_color='red', background_fill_color='red') error_plt.add_layout(cite) error_plt.add_layout( Label(text='Success', render_mode='css', text_color='white', border_line_color='green', background_fill_color='green')) Ncell_input = TextInput(value='72', title='No. of cells') Irrad_input = TextInput(value='800', title='Irradiance') Temp_input = TextInput(value='25', title='Temperature (Celcius)') Isc_input = TextInput(value='9.25', title='I_sc at STC') Im_input = TextInput(value='8.76', title='I_m') Voc_input = TextInput(value='45.9', title='V_oc') Vm_input = TextInput(value='37.2', title='V_m') Isc_N_input = TextInput(value='7.47', title='I_sc at NOTC(G=800, T=45C)') Data_input = TextInput(value='100', title='Data Size') submit = Button(label='Submit', button_type='success') download_button_STC = Button(label='Download data (STC)') download_button_GT = Button(label='Download data (Translated)') def get_inputs(): return (float(Ncell_input.value), float(Irrad_input.value), float(Temp_input.value), float(Voc_input.value), float(Isc_input.value), float(Vm_input.value), float(Im_input.value), float(Isc_N_input.value), float(Data_input.value)) def update_plot(event): N, G, T, V, I, Vm, Im, I_N, datapoints = get_inputs() print('#' * 30) print('Updating the plot') print('#' * 30) updated_data = iv.iv_data(N, G, T, V, I, Vm, Im, I_N, datapoints) source.data = updated_data[0] source_translated.data = updated_data[1] res_source.data = updated_data[2] global status_param status_param = updated_data[3] print(status_param) if (status_param.success == True): print('Inside success') cite = Label(text='Successful Parameter Extraction', render_mode='css', text_color='white', border_line_color='green', background_fill_color='green') else: print('Inside fail') cite = Label(text='Parameter extraction not converging', render_mode='css', text_color='white', border_line_color='red', background_fill_color='red') error_plt = Figure( plot_width=100, plot_height=50, toolbar_location=None, ) error_plt.add_layout(cite) layout.children[2].children[1] = error_plt def update_success(): if (status_param.success == True): print('Inside success') cite = Label(text='Success', render_mode='css', text_color='white', border_line_color='green', background_fill_color='green') else: print('Inside fail') cite = Label(text='False', render_mode='css', text_color='white', border_line_color='red', background_fill_color='red') error_plt = Figure( plot_width=100, plot_height=50, toolbar_location=None, ) error_plt.add_layout(cite) layout.children[2].children[1] = error_plt submit.on_click(update_plot) download_button_STC.js_on_click( CustomJS(args=dict(source=source), code=open(join(dirname(__file__), "download.js")).read())) download_button_GT.js_on_click( CustomJS(args=dict(source=source_translated), code=open(join(dirname(__file__), "download.js")).read())) #doc.add_periodic_callback(update_success, 1000) layout = row( plot, column(Ncell_input, Irrad_input, Temp_input, Isc_input, Im_input, Voc_input, Vm_input, Isc_N_input, Data_input, submit, download_button_STC, download_button_GT), column(sig_plot, error_plt)) return (layout)
def modify_doc(doc): """Add plots to the document Parameters ---------- doc : [type] A Bokeh document to which plots can be added """ curDir = os.path.dirname(__file__) root = tk.Tk() root.withdraw() ProgressBar().register() filepath = filedialog.askopenfilename() filename = filepath[filepath.rfind('/') + 1:filepath.rfind('.')] monteData = dd.read_csv(filepath) monteData.fillna(0) plotData = monteData.compute() gc.collect() plotData.drop_duplicates(subset='L-string', inplace=True) plotData.reset_index() for i in range(2, 6): plotData['{}-gram'.format(i)] = plotData['L-string'].apply( lambda x: [x[j:j + i] for j in range(0, len(x), i)]) gc.collect() scatter = ColumnDataSource(data=plotData) line = ColumnDataSource(data=dict(x=[0, 0], y=[0, 0])) rule1 = ColumnDataSource(data=dict(x=[0, 0], y=[0, 0])) rule2 = ColumnDataSource(data=dict(x=[0, 0], y=[0, 0])) polygon = ColumnDataSource(data=dict(x=[0], y=[0])) rule1_poly = ColumnDataSource(data=dict(x=[0, 0], y=[0, 0])) rule2_poly = ColumnDataSource(data=dict(x=[0, 0], y=[0, 0])) palette.reverse() mapper = log_cmap(field_name='Area', palette=palette, low=0, high=500) tooltips1 = [ ('index', '$index'), ('F', '@{% of F}{0.0%}'), ('+', '@{% of +}{0.0%}'), ('-', '@{% of -}{0.0%}'), ] tooltips2 = [ ('index', '$index'), ('F', '@{Longest F sequence}'), ('+', '@{Longest + sequence}'), ('-', '@{Longest - sequence}'), ] plots_width = 500 plots_height = 500 p1 = figure(plot_width=plots_width, plot_height=plots_height, tools='pan,wheel_zoom,box_zoom,reset,tap,save', title="Area", output_backend="webgl", tooltips=tooltips1) p1.xaxis.axis_label = 'Area' p1.yaxis.axis_label = '% of character' p1.scatter('Area', '% of F', size=7, source=scatter, color=mapper, alpha=0.6, nonselection_fill_color=mapper) p2 = figure(plot_width=plots_width, plot_height=plots_height, tools='pan,wheel_zoom,box_zoom,reset,tap,save', title="Area", output_backend="webgl", tooltips=tooltips2) p2.xaxis.axis_label = 'Area' p2.yaxis.axis_label = 'Length of sequence' p2.scatter('Area', 'Longest F sequence', size=7, source=scatter, fill_color='red', color=mapper, alpha=0.6, nonselection_fill_color=mapper) p3 = figure(plot_width=plots_width, plot_height=plots_height, tools='pan,wheel_zoom,box_zoom,reset,tap,save', title="Selected Creature", output_backend="webgl") p3.axis.visible = False p3.grid.visible = False p3.line(x='x', y='y', line_color='red', source=line) p3.multi_polygons(xs='x', ys='y', source=polygon) p4 = figure(plot_width=plots_width, plot_height=plots_height, tools='pan,wheel_zoom,box_zoom,reset,tap,save', title="Area", output_backend="webgl") p4.scatter('Area', 'Angle', size=7, source=scatter, color=mapper, alpha=0.6, nonselection_fill_color=mapper) p4.xaxis.axis_label = 'Area' p4.yaxis.axis_label = 'Angle (degrees)' p5 = figure(plot_width=plots_width, plot_height=plots_height // 2, title="Rule 1", output_backend="webgl") p5.line(x='x', y='y', line_color='red', source=rule1) p5.multi_polygons(xs='x', ys='y', source=rule1_poly) p5.axis.visible = False p5.grid.visible = False p6 = figure(plot_width=plots_width, plot_height=plots_height // 2, title="Rule 2", output_backend="webgl") p6.line(x='x', y='y', line_color='red', source=rule2) p6.multi_polygons(xs='x', ys='y', source=rule2_poly) p6.axis.visible = False p6.grid.visible = False L_string = Paragraph(text='Select creature', width=1500) grams = PreText(text='Select creature', width=400) rule_text = PreText(text='Select creature', width=400) area_label = Label( x=0, y=450, x_units='screen', y_units='screen', text='Select creature', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0, ) length_label = Label( x=0, y=420, x_units='screen', y_units='screen', text='Select creature', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0, ) p3.add_layout(area_label) p3.add_layout(length_label) def plot_source(coords): """[summary] Returns ------- [type] [description] """ instance_linestring = LineString(coords[:, 0:2]) instance_patch = instance_linestring.buffer(0.5) instance_x, instance_y = instance_patch.exterior.coords.xy return instance_x, instance_y def mapper(string, angle): theta = 0 num_chars = len(string) coords = np.zeros((num_chars + 1, 3), np.double) def makeRotMat(theta): rotMat = np.array(((cos(theta), -sin(theta), 0), (sin(theta), cos(theta), 0), (0, 0, 1))) return rotMat rotVec = makeRotMat(theta) dir_vec = np.array((0, 1, 0), np.float64) i = 1 for c in string: if c == 'F': coords[i] = (coords[i - 1] + (1 * dir_vec)) i += 1 if c == '-': theta = theta - angle rotVec = makeRotMat(theta) dir_vec = np.dot(rotVec, dir_vec) if c == '+': theta = theta + angle rotVec = makeRotMat(theta) dir_vec = np.dot(rotVec, dir_vec) coords = np.delete(coords, np.s_[i:], 0) return coords def plot_creature(event): line.data = dict(x=[0, 0], y=[0, 0]) polygon.data = dict(x=[0, 0], y=[0, 0]) rule1.data = dict(x=[0, 0], y=[0, 0]) rule2.data = dict(x=[0, 0], y=[0, 0]) rule1_poly.data = dict(x=[0, 0], y=[0, 0]) rule2_poly.data = dict(x=[0, 0], y=[0, 0]) L_string.text = 'Select creature' area_label.text = 'Select creature' length_label.text = 'Select creature' rule_text.text = 'Select creature' if len(scatter.selected.indices) > 0: creature_index = scatter.selected.indices[0] creature = plotData.iloc[creature_index, :] coords = np.array(ast.literal_eval(creature['Coordinates'])) L_string.text = '{}'.format(creature['L-string']) area_label.text = 'Area: {:.2f}'.format(creature['Area']) length_label.text = 'Length of L-string: {}'.format( len(creature['L-string'])) gram_frame_1 = pd.DataFrame.from_dict( { '2-gram': creature['2-gram'], '3-gram': creature['3-gram'], '4-gram': creature['4-gram'], '5-gram': creature['5-gram'], }, orient='index').T counts = [ pd.value_counts( gram_frame_1[i]).reset_index().astype(str).apply( ' '.join, 1) for i in gram_frame_1 ] out = pd.concat(counts, 1).fillna('') out.columns = gram_frame_1.columns grams.text = str(tabulate(out, headers='keys')) creature_linestring = LineString(coords[:, 0:2]) creature_patch = creature_linestring.buffer(0.5) patch_x, patch_y = creature_patch.exterior.coords.xy x_points = [list(patch_x)] y_points = [list(patch_y)] for i, _ in enumerate(creature_patch.interiors): x_in, y_in = creature_patch.interiors[i].coords.xy x_points.append(list(x_in)) y_points.append(list(y_in)) x_points = [[x_points]] y_points = [[y_points]] line.data = dict(x=coords[:, 0], y=coords[:, 1]) polygon.data = dict(x=x_points, y=y_points) p3.match_aspect = True rules = ast.literal_eval(creature['Rules']) rules = rules['X'] rules = rules['options'] rule_text.text = 'Rule 1: \t' + \ rules[0] + '\n' + 'Rule 2: \t' + rules[1] if any(char == 'F' for string in rules[0] for char in string): rule1_c = mapper(rules[0], creature['Angle']) rule1_morphology = LineString(rule1_c[:, 0:2]) rule1_patch = rule1_morphology.buffer(0.5) rpatch_x, rpatch_y = rule1_patch.exterior.coords.xy r1_points_x = [list(rpatch_x)] r1_points_y = [list(rpatch_y)] for i, _ in enumerate(rule1_patch.interiors): x_in, y_in = creature_patch.interiors[i].coords.xy r1_points_x.append(list(x_in)) r1_points_y.append(list(y_in)) r1_points_x = [[r1_points_x]] r1_points_y = [[r1_points_y]] rule1.data = dict(x=rule1_morphology.coords.xy[0], y=rule1_morphology.coords.xy[1]) rule1_poly.data = dict(x=r1_points_x, y=r1_points_y) p5.match_aspect = True if any(char == 'F' for string in rules[1] for char in string): rule2_c = mapper(rules[1], creature['Angle']) rule2_morphology = LineString(rule2_c[:, 0:2]) rule2_patch = rule2_morphology.buffer(0.5) r2patch_x, r2patch_y = rule2_patch.exterior.coords.xy r2_points_x = [list(r2patch_x)] r2_points_y = [list(r2patch_y)] for i, _ in enumerate(rule2_patch.interiors): x_in, y_in = creature_patch.interiors[i].coords.xy r2_points_x.append(list(x_in)) r2_points_y.append(list(y_in)) r2_points_x = [[r2_points_x]] r2_points_y = [[r2_points_y]] rule2.data = dict(x=rule2_morphology.coords.xy[0], y=rule2_morphology.coords.xy[1]) rule2_poly.data = dict(x=r2_points_x, y=r2_points_y) p6.match_aspect = True else: line.data = dict(x=[0, 0], y=[0, 0]) polygon.data = dict(x=[0, 0], y=[0, 0]) rule1.data = dict(x=[0, 0], y=[0, 0]) rule2.data = dict(x=[0, 0], y=[0, 0]) rule1_poly.data = dict(x=[0, 0], y=[0, 0]) rule2_poly.data = dict(x=[0, 0], y=[0, 0]) L_string.text = 'Select creature' area_label.text = 'Select creature' length_label.text = 'Select creature' rule_text.text = 'Select creature' p1.on_event(Tap, plot_creature) p2.on_event(Tap, plot_creature) p4.on_event(Tap, plot_creature) top_row = row(L_string) middle_row = row(p1, p2, p4) bottom_row_right = column(p5, p6) bottom_row_middle = column(grams, rule_text) bottom_row = row(p3, Spacer(width=50), bottom_row_middle, Spacer(width=50), bottom_row_right) layout = column(top_row, middle_row, bottom_row) doc.add_root(layout)
line_source = ColumnDataSource(data=dict(x=x_line, y=y_line)) point_source = ColumnDataSource(data=dict(x=x_points, y=y_points)) plot = figure(y_range=(-5, 120), x_range=(-5, 100), plot_width=600, plot_height=400, x_axis_label='[S]: substrate concentration (μM)', y_axis_label='initial velocity (μM/s)', title='Michaelis-Menten Kinetics with Inhibition') plot.line('x', 'y', source=line_source, line_width=3, line_alpha=0.6, color='black') plot.circle('x', 'y', source=point_source, size=10, color='black') # set up static line and annotations plot.line(x_line, y_line, line_width=5, color='blue', line_alpha=0.3) plot.circle(x_points, y_points, size=10, color='blue', line_alpha=0.3) mytext = Label(x=10, y=87, text='[I] = 0 (μM)', text_color="blue", text_alpha=0.5) plot.add_layout(mytext) # add axes lines vline = Span(location=0, dimension='height', line_color='black', line_width=1, line_alpha=0.3) hline = Span(location=0, dimension='width', line_color='black', line_width=1, line_alpha=0.3) plot.renderers.extend([vline, hline]) # set up java script callback function and widgets to make plot interactive ci_slider = Slider(start=0, end=100, value=0, step=1, title="[I] (μM)") ki_slider = Slider(start=1, end=100, value=50, step=1, title="Ki (μM)") inhib_select = Select(title="Inhibition Type:", value="competitive", options=["competitive", "noncompetitive", "uncompetitive"]) callback = CustomJS(args=dict(LineSource=line_source, PointSource=point_source,
def draw_vectors(): driver = webdriver.Chrome(os.path.join(BASE_DIR, "chromedriver"), options=options) df = pd.read_csv(os.path.join(OUTPUTS_DIR, "normalized_future_vectors.csv")) filter_list = { (5, 6), (5, 7), (6, 7), (8, 9), (8, 10), (9, 10), (11, 12), (11, 13), (12, 13), } comb = list(combinations(range(5, len(df.columns)), 2)) comb = [c for c in comb if c not in filter_list] for idx, coord in enumerate(comb, 1): x, y = coord X = df[df.columns[x]].to_list() Y = df[df.columns[y]].to_list() tsne_df = pd.DataFrame(zip(X, Y), index=range(len(X)), columns=["x_coord", "y_coord"]) tsne_df["title"] = df["title"].to_list() tsne_df["cluster_no"] = df["cluster"].to_list() colormap = {3: "#ffee33", 2: "#00a152", 1: "#2979ff", 0: "#d500f9"} # colormap = {3: "#bdbdbd", 2: "#bdbdbd", 1: "#bdbdbd", 0: "#d500f9"} # colormap = {3: "#bdbdbd", 2: "#bdbdbd", 1: "#2979ff", 0: "#bdbdbd"} # colormap = {3: "#bdbdbd", 2: "#00a152", 1: "#bdbdbd", 0: "#bdbdbd"} # colormap = {3: "#ffee33", 2: "#bdbdbd", 1: "#bdbdbd", 0: "#bdbdbd"} only_one_cluster = pd.DataFrame(tsne_df.loc[tsne_df.cluster_no == 3]) colors = [colormap[x] for x in only_one_cluster["cluster_no"]] only_one_cluster["color"] = colors plot_data = ColumnDataSource(data=only_one_cluster.to_dict( orient="list")) plot = figure( # title='TSNE Twitter BIO Embeddings', plot_width=1600, plot_height=1600, active_scroll="wheel_zoom", output_backend="svg", x_range=(-1.1, 1.1), y_range=(-1.1, 1.1), ) plot.add_tools(HoverTool(tooltips="@title")) plot.circle( source=plot_data, x="x_coord", y="y_coord", line_alpha=0.6, fill_alpha=0.6, size=20, fill_color="color", line_color="color", ) plot.yaxis.axis_label_text_font_size = "25pt" plot.yaxis.major_label_text_font_size = "25pt" plot.xaxis.axis_label_text_font_size = "25pt" plot.xaxis.major_label_text_font_size = "25pt" start_x, end_x = df.columns[x].split("|") start_y, end_y = df.columns[y].split("|") start_x = start_x.strip() end_x = end_x.strip() start_y = start_y.strip() end_y = end_y.strip() plot.title.text_font_size = value("32pt") plot.xaxis.visible = True # plot.xaxis.bounds = (0, 0) plot.yaxis.visible = True label_opts1 = dict( x_offset=0, y_offset=750, text_font_size="30px", ) msg1 = end_y caption1 = Label(text=msg1, **label_opts1) label_opts2 = dict( x_offset=0, y_offset=-750, text_font_size="30px", ) msg2 = start_y caption2 = Label(text=msg2, **label_opts2) label_opts3 = dict( x_offset=600, y_offset=0, text_font_size="30px", ) msg3 = end_x caption3 = Label(text=msg3, **label_opts3) label_opts4 = dict( x_offset=-750, y_offset=0, text_font_size="30px", ) msg4 = start_x caption4 = Label(text=msg4, **label_opts4) plot.add_layout(caption1, "center") plot.add_layout(caption2, "center") plot.add_layout(caption3, "center") plot.add_layout(caption4, "center") plot.background_fill_color = None plot.border_fill_color = None plot.grid.grid_line_color = None plot.outline_line_color = None plot.yaxis.fixed_location = 0 plot.xaxis.fixed_location = 0 plot.toolbar.logo = None plot.toolbar_location = None print(idx) export_svg( plot, filename=f"svgs/{idx}.svg", webdriver=driver, height=1600, width=1600, ) export_png( plot, filename=f"pngs/{idx}.png", webdriver=driver, height=1600, width=1600, )
def define_figure(width, height, dataframe, hover, itype): """ Prepare bokeh figure heatmap as intended """ # Mapper colors = [ '#800000', '#860000', '#8c0000', '#930000', '#990000', '#9f0000', '#a60000', '#ac0000', '#b20000', '#b90000', '#bf0000', '#c50000', '#cc0000', '#d20000', '#d80000', '#df0000', '#e50000', '#eb0000', '#f20000', '#f80000', '#ff0000', '#ff0700', '#ff0e00', '#ff1500', '#ff1c00', '#ff2300', '#ff2a00', '#ff3100', '#ff3800', '#ff3f00', '#ff4600', '#ff4d00', '#ff5400', '#ff5b00', '#ff6200', '#ff6900', '#ff7000', '#ff7700', '#ff7e00', '#ff8500', '#ff8c00', '#ff9100', '#ff9700', '#ff9d00', '#ffa300', '#ffa800', '#ffae00', '#ffb400', '#ffba00', '#ffbf00', '#ffc500', '#ffcb00', '#ffd100', '#ffd600', '#ffdc00', '#ffe200', '#ffe800', '#ffed00', '#fff300', '#fff900', '#ffff00', '#f2ff00', '#e5ff00', '#d8ff00', '#ccff00', '#bfff00', '#b2ff00', '#a5ff00', '#99ff00', '#8cff00', '#7fff00', '#72ff00', '#66ff00', '#59ff00', '#4cff00', '#3fff00', '#33ff00', '#26ff00', '#19ff00', '#0cff00', '#00ff00', '#0afc0a', '#15fa15', '#1ff81f', '#2af62a', '#34f434', '#3ff13f', '#49ef49', '#54ed54', '#5eeb5e', '#69e969', '#74e674', '#7ee47e', '#89e289', '#93e093', '#9ede9e', '#a8dba8', '#b3d9b3', '#bdd7bd', '#c8d5c8', '#d3d3d3' ] colors.reverse() mapper = LinearColorMapper(palette=colors, low=0, high=100) #Bokeh figure p = figure( plot_width=width, plot_height=height, #title="Example freq", y_range=list(dataframe.shortName.drop_duplicates()), x_range=list(dataframe.Position.drop_duplicates()), tools=["hover", "tap", "save", "reset", "wheel_zoom"], x_axis_location="above", active_drag=None, toolbar_location="right", toolbar_sticky=False, min_border_top=200, #leave some space for x-axis artificial labels min_border_bottom=0, ) # Create rectangle for heatmap mysource = ColumnDataSource(dataframe) p.rect( y="shortName", x="Position", width=1, height=1, source=mysource, line_color="white", fill_color=transform(itype, mapper), # set visual properties for selected glyphs selection_line_color="black", selection_fill_color=transform(itype, mapper), # set visual properties for non-selected glyphs nonselection_fill_color=transform(itype, mapper), nonselection_fill_alpha=1, nonselection_line_alpha=1, nonselection_line_color="white") #Very poor way of creating X-axis labels. Necessary for having linejumps inside the axis labels x_cord = 0 y_cord = len(list(dataframe.Id.drop_duplicates()) ) + 11 #Position: 11 spaces above the plot's top border foolabel = Label(x=-1, y=y_cord, text='\nA: \nB: \nC: \nF: \n\n\nA: \nB: \nC: \nF: \n', render_mode='css', border_line_alpha=1.0, text_font_size="10pt", background_fill_color="#FFFFFF") p.add_layout(foolabel) #Fore every unique position in the set, add a label in axis for position in list(dataframe.Position.drop_duplicates()): position = position.replace("Ligand", "Lig\n\n\n\n\n") foolabel = Label(x=x_cord, y=y_cord, text=position, render_mode='css', border_line_alpha=1.0, background_fill_color="#FFFFFF", text_font_size="10pt") p.add_layout(foolabel) x_cord += 1 # Setting axis p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.xaxis.major_label_text_font_size = "10pt" p.yaxis.major_label_text_font_size = "10pt" p.xaxis.visible = False p.axis.major_label_standoff = 0 p.xaxis.major_label_orientation = 1 # Adding hover p.add_tools(hover) # Needed later return (mysource, p)
DAILY_POS_COUNT = [item[2] for item in csvdata] data = { 'DATE': DATE, 'POS_COUNT': POS_COUNT, 'DAILY_POS_COUNT': DAILY_POS_COUNT } x = data['DATE'] pos_counts = data['POS_COUNT'] daily_counts = data['DAILY_POS_COUNT'] source = ColumnDataSource( data=dict(x=x, pos_counts=pos_counts, daily_counts=daily_counts)) mytext1_ypos = int(pos_counts[len(pos_counts) - 1]) - 200 mytext1 = Label(x=1, y=mytext1_ypos, text='Day 0 (first detected case): 07 March 2020') plot1 = figure(x_range=FactorRange(*x), plot_width=700, plot_height=350, title="Number of positive cases (Cumulative)") plot1.vbar('x', top='pos_counts', width=0.9, source=source) plot1.title.text_font_size = "15pt" plot1.xaxis.axis_label = "Day" plot1.xaxis.axis_label_text_font = "times" plot1.xaxis.axis_label_text_font_style = "normal" plot1.xaxis.major_label_text_font_size = "10pt" plot1.xaxis.major_label_orientation = np.pi / 2 plot1.xaxis.axis_label_text_font_size = "15pt" plot1.xaxis.ticker = SingleIntervalTicker(interval=4)
def graph(): global df if request.method == 'POST': try: symbol = request.form["ticker"] time = request.form.get('time_dur') chart = request.form.get('chart_type') val, start = duration(time) end = dt(dt.now().year, dt.now().month, dt.now().day) df = data.DataReader(name=symbol, data_source="iex", start=start, end=end) def inc_dec(c, o): if c > o: value = "Increase" elif c < o: value = "Decrease" else: value = "Equal" return value df["status"] = [inc_dec(c, o) for c, o in zip(df.close, df.open)] df["middle"] = (df.open + df.close) / 2 df["height"] = abs(df.close - df.open) highest = max(df.close) lowest = min(df.close) p = figure(x_axis_type='datetime', plot_width=1600, plot_height=500, background_fill_color="#00004d", sizing_mode="scale_both", toolbar_location="above") p.title.text = symbol + " Chart" p.grid.grid_line_alpha = 0.3 hours_12 = 12 * 60 * 60 * 1000 df.index = pd.to_datetime(df.index) cds = ColumnDataSource(data=dict(x=df.index, y0=df.high, y1=df.low, volume=df.volume, c0=df.close)) hover = HoverTool(tooltips=[("Peak", "@y0"), ("Volume", "@volume")], names=["seg"]) p.add_tools(hover) if chart == "candle": p.segment(x0='x', y0='y0', x1='x', y1='y1', color="white", name="seg", source=cds) p.rect(df.index[df.status == "Increase"], df.middle[df.status == "Increase"], hours_12, df.height[df.status == "Increase"], fill_color="#00e673", line_color="black") p.rect(df.index[df.status == "Decrease"], df.middle[df.status == "Decrease"], hours_12, df.height[df.status == "Decrease"], fill_color="#ff0066", line_color="black") elif chart == "line": p.line(x='x', y='c0', color="green", line_width=2, name="seg", source=cds) high_label = Label(x=df.index[df.close == highest][0], y=highest, x_offset=5, y_offset=-5, text="H", text_color="white", text_font_size="10pt", text_font_style="bold") low_label = Label(x=df.index[df.close == lowest][0], y=lowest, text="L", text_color="white", text_font_size="10pt", text_font_style="bold") p.add_layout(high_label) p.add_layout(low_label) script1, div1 = components(p) cdn_js = CDN.js_files[0] cdn_css = CDN.css_files[0] return render_template( "index.html", script1=script1, div1=div1, cdn_css=cdn_css, cdn_js=cdn_js, day_low=round(df.low[-1], 2), day_high=round(df.high[-1], 2), month_low=round(min(df.low), 2), month_high=round(max(df.high), 2), return_month=round( ((df.close[-1] - df.close[0]) / df.close[0]) * 100, 2), moving_avg=round(df.close.mean(), 2), extra="info.html", val=val) except: return render_template("index.html", text="Please enter a valid IEX ticker.")
select_short.value, select_lfield.value, select_cfield.value, select_rfield.value]) batting_order_text.text = batting_lineup_list """ position_select_list = [ select_pitcher_dh, select_catcher, select_first, select_second, select_third, select_short, select_lfield, select_cfield, select_rfield ] # Add labels to field plot pitcher_dh_lab = Label( x=0, y=math.sqrt(2) / 2, text=" " + select_pitcher_dh.value + " ", x_offset=0, y_offset=5, #render_mode='canvas', border_line_color='black', background_fill_color='white', text_align='center', # options are 'left', 'right', 'center' text_baseline="alphabetic") catcher_lab = Label(x=0, y=0, text=' ' + select_catcher.value + ' ', x_offset=0, y_offset=-10, border_line_color='black', background_fill_color='white', text_align='center', text_baseline="alphabetic")
# define color when (not-) selected selected_node = Circle(fill_alpha=0.8, fill_color=color[0], line_color=None) nonselected_node = Circle(fill_alpha=0.6, fill_color=color[3], line_color=None) # and trigger it correctly n.selection_glyph = selected_node n.nonselection_glyph = nonselected_node #dir(n.data_source.selected) #n.data_source.on_change('selected', update_stacked_bars) n.data_source.selected.on_change('indices', update_stacked_bars) #inidcator for data-load source_ind = ColumnDataSource(data=dict(x=[1], y=[1], color=["green"])) fig_indicator = figure(x_range=(0, 8), y_range=(0, 2), toolbar_location=None, tools="", plot_height=50, plot_width=300) label = Label(x=1.8, y=.8, text="Data is Loaded!", text_alpha=1) fig_indicator.add_layout(label) fig_indicator.axis.visible = False fig_indicator.grid.visible = False fig_indicator.outline_line_alpha = 0 fig_indicator.circle("x", "y", size=25, fill_alpha=0.6, fill_color="color", line_color=None, source=source_ind) ### Legend for Lineloadings/LODF colors line_legend_dict = create_line_legend(60, 110) source_line_legend = ColumnDataSource(line_legend_dict) legend_lines = figure(plot_width=300, plot_height=80, x_range=(60, 110.1), y_range=(0, 1), toolbar_location=None, tools="", title="N-0 Lineloadings in %" )
def percentile_plot(data, bin_size, fy_select: str, same_title: np.ndarray = None, title_changed: np.ndarray = None, bc: str = "#f0f0f0", bfc: str = "#fafafa"): def _percent_norm(x): return x / len(data) * 100 bins = np.arange(-50, 250.0, bin_size) x_label = 'Percentage' bin_size = bins[1] - bins[0] x_range = [-10, 25] s = bokeh_fig_init(x_range=x_range, x_label=x_label, y_label='Percentage of Total Employees', bc=bc, bfc=bfc, tools="xpan,xwheel_zoom,xzoom_in,xzoom_out,save,reset") N_bin, percent_bin = np.histogram(data, bins=bins) fy_inflation = INFLATION_DATA[fy_select] y_inflation = [0, max(_percent_norm(N_bin) + 5)] s.line([fy_inflation] * 2, y_inflation, color='red', width=2) l1 = Label(x=INFLATION_DATA[fy_select], y=y_inflation[1], x_offset=15, y_offset=-5, x_units='data', y_units='data', angle=90 / 180 * 3.14159, text_font_size='12px', text_align='right', text=f'CPI Inflation, {fy_inflation:.2}%') s.add_layout(l1) s.y_range.end = y_inflation[1] s.vbar(x=percent_bin[:-1], top=_percent_norm(N_bin), width=0.95 * bin_size, fill_color=None, fill_alpha=0.5, line_color='black', legend_label='All') if same_title is not None: N_bin1, percent_bin1 = np.histogram(data[same_title], bins=bins) s.vbar(x=percent_bin1[:-1], top=_percent_norm(N_bin1), width=1.0 * bin_size, fill_color="#f8b739", fill_alpha=0.5, line_color=None, legend_label='Unchanged') if title_changed is not None: N_bin2, percent_bin2 = np.histogram(data[title_changed], bins=bins) s.vbar(x=percent_bin2[:-1], top=_percent_norm(N_bin2), width=1.0 * bin_size, fill_color="purple", fill_alpha=0.5, line_color=None, legend_label='Changed') s.legend.orientation = 'vertical' s.legend.location = 'top_right' s.yaxis[0].formatter = PrintfTickFormatter(format="%i%%") st.bokeh_chart(s, use_container_width=True)
elif sel == 'Deaths': r.data_source.data['y'] = data['new_deaths'] textbox.value = 'New death cases' menu_type = [('New confirmed cases', "Cases"), ('Deaths', "Deaths")] dropdown_state = Dropdown(label="Case confirmed or death", button_type="warning", menu=menu_type) dropdown_state.on_click(update) citation = Label(x=0, y=10, x_units='screen', y_units='screen', text='Source: ' + g1_source + '. Last update: ' + g1_last_update, render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0, text_font_size='10.5px') p.add_layout(citation) ### second part: table for races url2 = 'cdph-race-ethnicity.csv' def isNone(x): if x != None: return False else:
def x_update(): global x while True: time.sleep(conf.BEACON_FREQUENCY) x += conf.BEACON_FREQUENCY Thread(target=x_update).start() # add labels label1 = Label(x=0, y=0, x_units='screen', y_units='screen', text='saved: 0/0', render_mode='css', background_fill_alpha=0) label2 = Label(x=0, y=20, x_units='screen', y_units='screen', text='max=0, min=0, avg=0', render_mode='css', background_fill_alpha=0) plot_line.add_layout(label1) plot_line.add_layout(label2) # add a button label_num = 0
cases_summary['day'] = cases_summary['day'].astype('str') source = ColumnDataSource(cases_summary) hover = HoverTool(line_policy='next') hover.tooltips = [ ('Date', '@x{%F}'), ('Cases', '@y{0000}') # @$name gives the value corresponding to the legend ] hover.formatters = {'@x': 'datetime'} p.add_tools(hover) citation = Label(x=0, y=0, x_units='screen', y_units='screen', text='Last Updated : {}'.format(latest_date), render_mode='css', text_font_size='12px') p.add_layout(citation, 'above') div = Div(text="""<b>Source:</b> COVID-19 REST API for India: <a href='https://api.rootnet.in/covid19-in/stats/history' target="_blank"> The Ministry of Health and Family Welfare</a> """, width=300, height=50, align='start') fig = column(p, div, sizing_mode='scale_both') tab1 = Panel(child=fig, title="All Cases - Statewise") #statewise death count over time
def drawGasPlot(combinedData, chemical, time, numToDateHashMap): p = figure(title="Gas Measure of " + chemical, x_axis_location=None, y_axis_location=None, x_axis_label='Map', y_axis_label='Map', tools="pan,wheel_zoom,reset,hover,save") # p.circle(x = facs['x'], y = facs['y'], color = 'blue', size = 15) sensor_measurements = findRanksBasedOnChemicalMeasurement( combinedData, chemical, time) rankSize = 10 print('wind direction is') print(combinedData[time][-1][1]) angle = combinedData[time][-1][1] print('sin shift {} and cos shift {}'.format(math.sin(math.radians(angle)), math.cos( math.radians(angle)))) print("date is ", numToDateHashMap[time]) for pair in sensor_measurements: if pair[0] == 1.0: p.circle(61, 21, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) elif pair[0] == 2.0: p.circle(66, 35, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) elif pair[0] == 3.0: p.circle(76, 41, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) elif pair[0] == 4.0: p.circle(88, 45, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) elif pair[0] == 5.0: p.circle(103, 43, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) elif pair[0] == 6.0: p.circle(102, 22, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) elif pair[0] == 7.0: p.circle(89, 3, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) elif pair[0] == 8.0: p.circle(74, 7, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) elif pair[0] == 9.0: p.circle(119, 42, size=pair[1] * 25, line_color="green", fill_color="green", fill_alpha=0.5) rankSize += 10 #show(p) p.circle(x=50, y=0, fill_alpha=0, size=1) p.circle(x=110, y=60, fill_alpha=0, size=1) p.add_layout( Arrow(end=VeeHead(size=35, fill_color='red'), line_color="red", x_start=65, y_start=53, x_end=65 - math.sin(math.radians(angle)), y_end=53 - math.cos(math.radians(angle)))) speed = Label(x=65, y=56, background_fill_color='white', text='wind speed: ' + str(combinedData[time][-1][3])) p.add_layout(speed) p.image_url(url=['https://i.imgur.com/Lz7D8KN.jpg'], x=46, y=65, w=82, h=70, global_alpha=.5) return p
'@mental_health'), ('% Maternity', '@maternity'), ('% Learning Disabilities', '@learning_dis'), ('% General Acute', '@general_acute'), ('Region', '@area')]) # Call the plotting function p = make_plot(ward_name) dates = np.unique(year_all) number_dates = np.arange(len(dates)) slider = Slider(title='Quarter', start=number_dates[0], end=number_dates[-1], step=1, value=number_dates[0]) label = Label(x=-0.9, y=55, text=str(dates[0]), text_font_size='20px') slider.on_change('value', update_plot) p.add_layout(label) # Make a selection object: select select = Select(title='Select Ward:', value='total', options=[ 'total', 'mental_health', 'maternity', 'learning_dis', 'general_acute' ]) select.on_change('value', update_plot) # Make a column layout of widgetbox(slider) and plot, and add it to the current document # Display the current document layout = column(p, widgetbox(slider), widgetbox(select))
kpis = [0.95, 0.02, 0.01, 0.02] kpi_data = {'kpi' : [0.95, 0.02, 0.01, 0.02], 'y' : [1,2,3,4], 'txt_kpi' : [k+0.03 for k in kpis], 'txt_y' : [i - 0.15 for i in [1,2,3,4]], 'txt_format' : [str(k*100) + ' %' for k in kpis]} kpi_source = ColumnDataSource(kpi_data) p_training_kpi = figure(plot_height = 250, plot_width = 250, title = "Max T%") p_training_kpi.title.align = 'center' p_training_kpi.annular_wedge(x=0, y=0, inner_radius=0.5, outer_radius=0.6, start_angle=-2*pi*max(kpi_data['kpi']), end_angle=0, color="green", alpha=0.6) citation = Label(x=0, y=-0.1, text=str(max(kpi_data['kpi'])*100) + ' %', render_mode='css', text_font_size = '20pt', text_align = 'center') p_training_kpi.add_layout(citation) dashboardize(p_training_kpi) p_indicators = figure(plot_height = 250, plot_width = 250, x_range = [0, 1.3]) p_indicators.hbar(y='y', height=0.5, left=0, right='kpi', fill_alpha = 0.6, source = kpi_source) p_indicators.circle(x = 'kpi',y = 'y', name = 'tip', alpha = 0, hover_alpha = 1, source = kpi_source) text_glyph = Text(x='txt_kpi', y="txt_y", text='txt_format') p_indicators.add_glyph(kpi_source, text_glyph) hover = HoverTool(tooltips = [('Value %','@kpi')],mode = 'hline', names =['tip']) p_indicators.add_tools(hover) dashboardize(p_indicators)