def generate_plot(data): # try: # data["Time:"] = [datetime.datetime.fromtimestamp(x) for x in data["Time:"]] # data['Time:'] = [x.strftime("%H:%M:%S.{} %p".format(x.microsecond % 100)) for x in data["Time:"]] # except TypeError: # pass print(data) source = ColumnDataSource(data) print(source.column_names) p = figure(x_axis_type='datetime') print(p.line(x='Time:', y='Temp Value:', source=source)) # p.line(x='Time:', y='Strain Value:', source=source) p.plot_width = 800 p.plot_height = 800 p.title.text = 'Device Readings' p.xaxis.axis_label = 'Time of Reading' p.yaxis.axis_label = 'Readings' hover = HoverTool() hover.tooltips = [ ('Time of Reading', '@{Time:}{%M:%S.%3N}'), ] hover.formatters = {"@{Time:}": "datetime"} p.add_tools(hover) # show(p) return p, source
months=dtformat, hours=dtformat, minutes=dtformat) # Add legend p_world_covid.legend.location = "top_left" # Add a hover tool hover = HoverTool() hover.tooltips = [ #('Type', "$name"), ('', '$name: @$name{0,0.} on @date{%a-%b-%d}'), ] # hover.mode = 'vline' hover.formatters = { '@date': 'datetime', # use 'datetime' formatter for '@date' field '$name': 'printf' # use 'printf' formatter for the name of the column } hover.renderers = glyphs p_world_covid.add_tools(hover) # # Extra formatting # for ax in p_world_covid.yaxis: # ax.axis_label_text_font_style = 'bold' # ax.axis_label_text_font_size = '16pt' # p_world_covid.title.text_font_size = '20pt' # p_world_covid.title.text_font_style = 'italic' glyphs_covid_world = glyphs # %% Make Buttons for state graph """
def create_bk_fig(x=None, xlab=None, x_min=None, x_max=None, ylab=None, fh=None, fw=None, title=None, pw=None, ph=None, x_axis_type="linear", y_axis_type="linear", x_name=None, y_name=None, **kwargs): """ Generates a bokeh figure Parameters ---------- x :obj:`DataArray` Contains x-axis data xlab : :obj:`str` X-axis label x_min : :obj:`float` Min x value x_max : :obj:`float` Max x value ylab : :obj:`str` Y-axis label fh: :obj:`int` True height of figure without legends, axes titles etc fw: :obj:`int` True width of figure without legends, axes etc title: :obj:`str` Title of plot pw: :obj:`int` Plot width including legends, axes etc ph: :obj:`int` Plot height including legends, axes etc x_axis_type: :obj:`str` Type of x-axis can be linear, log, or datetime y_axis_type: :obj:`str` Can be linear, log or datetime x_name: :obj:`str` Name of the column used for the x-axis. Mostly used to form tooltips y_name: :obj:`str` Name of the column used for the y-axis. Also used for tooltips add_grid: :obj:`bool` Whether or not to add grid add_title: :obj:`bool` Whether or not to add title to plot add_xaxis: :obj:`bool` Whether or not to add x-axis and tick marks add_yaxis: :obj:`bool` Add y-axis or not fix_plotsize: :obj:`bool` Enforce certain dimensions on plot. This is useful for ensuring a plot is not obscure by axes and other things. If activated, plot's dimensions will not be responsive. It utilises fw and fh. Returns ------- p : :obj:`Plot` A bokeh Plot object """ add_grid = kwargs.pop("add_grid", False) add_title = kwargs.pop("add_title", True) add_xaxis = kwargs.pop("add_xaxis", False) add_yaxis = kwargs.pop("add_yaxis", False) fix_plotsize = kwargs.pop("fix_plotsize", True) # addition plot specs pl_specs = kwargs.pop("pl_specs", {}) # additional axis specs ax_specs = kwargs.pop("ax_specs", {}) # ticker specs ti_specs = kwargs.pop("ti_specs", {}) plot_specs = dict(background="white", border_fill_alpha=0.1, border_fill_color="white", min_border=3, name="plot", outline_line_dash="solid", outline_line_width=2, outline_line_color="#017afe", outline_line_alpha=0.4, output_backend="canvas", sizing_mode="stretch_width", title_location="above", toolbar_location="above") plot_specs.update(pl_specs) axis_specs = dict(minor_tick_line_alpha=0, axis_label_text_align="center", axis_label_text_font="monospace", axis_label_text_font_size="10px", axis_label_text_font_style="normal", major_label_orientation="horizontal") axis_specs.update(ax_specs) tick_specs = dict(desired_num_ticks=5) tick_specs.update(ti_specs) # Define frame width and height # This is the actual size of the plot without the titles et al if fix_plotsize and not(fh or fw): fw = int(0.98 * pw) fh = int(0.93 * ph) # define the axes ranges x_range = DataRange1d(name="p_x_range", only_visible=True) y_range = DataRange1d(name="p_y_range", only_visible=True) if x_min is not None and x_max is not None and x_name.lower() in ["channel", "frequency"]: x_range = Range1d(name="p_x_range", start=x_min, end=x_max) y_range.only_visible = False # define items to add on the plot p_htool = HoverTool(tooltips=[(x_name, "$x"), (y_name, "$y")], name="p_htool", point_policy="snap_to_data") if x_name.lower() == "time": p_htool.tooltips[0] = (x_name, "$x{%d-%m-%Y %H:%M}") p_htool.formatters = {"$x": "datetime"} p_toolbar = Toolbar(name="p_toolbar", tools=[p_htool, BoxSelectTool(), BoxZoomTool(), # EditTool(), # BoxEditTool(), # RangeTool(), LassoSelectTool(), PanTool(), ResetTool(), SaveTool(), UndoTool(), WheelZoomTool()]) p_ticker = BasicTicker(name="p_ticker", **tick_specs) # select the axis scales for x and y if x_axis_type == "linear": x_scale = LinearScale(name="p_x_scale") # define the axes and tickers p_x_axis = LinearAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "datetime": x_scale = LinearScale(name="p_x_scale") # define the axes and tickers p_x_axis = DatetimeAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "log": x_scale = LogScale(name="p_x_scale") p_x_axis = LogAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) if y_axis_type == "linear": y_scale = LinearScale(name="p_y_scale") # define the axes and tickers p_y_axis = LinearAxis(axis_label=ylab, name="p_y_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "datetime": y_scale = LinearScale(name="p_y_scale") # define the axes and tickers p_y_axis = DatetimeAxis(axis_label=xlab, name="p_y_axis", ticker=p_ticker, **axis_specs) elif y_axis_type == "log": y_scale = LogScale(name="p_y_scale") # define the axes and tickers p_y_axis = LogAxis(axis_label=ylab, name="p_y_axis", ticker=p_ticker, **axis_specs) # Create the plot object p = Plot(plot_width=pw, plot_height=ph, frame_height=fh, frame_width=fw, toolbar=p_toolbar, x_range=x_range, x_scale=x_scale, y_range=y_range, y_scale=y_scale, **plot_specs) if add_title: p_title = Title(align="center", name="p_title", text=title, text_font_size="24px", text_font="monospace", text_font_style="bold",) p.add_layout(p_title, "above") if add_xaxis: p.add_layout(p_x_axis, "below") if add_yaxis: p.add_layout(p_y_axis, "left") if add_grid: p_x_grid = Grid(dimension=0, ticker=p_ticker) p_y_grid = Grid(dimension=1, ticker=p_ticker) p.add_layout(p_x_grid) p.add_layout(p_y_grid) return p
click_policy='hide', title="Click on States to Switch ON/OFF", title_text_font_style="bold") p.add_layout(legend1, 'right') p.add_layout(legend2, 'right') 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,
line_color="orange", muted_alpha=0.2, line_dash="1 8", legend_label="Chania Province") p.circle(x='dates', y='Chania', source=source, fill_color="orange", muted_alpha=0.2, size=4, legend_label="Chania Province") p.legend.location = "top_left" p.y_range.start = 0 p.x_range.start = df_infections.index[0] - timedelta(1) p.xaxis.formatter.days = '%d/%m/%Y' p.legend.click_policy = 'mute' from bokeh.models.tools import HoverTool hover = HoverTool() hover.tooltips = [ ('Date', '@dates{%d %b %Y}'), ('Chania', '@Chania{0,0}'), ('Crete', '@Crete{0,0}'), ] hover.formatters = {"@dates": "datetime"} p.add_tools(hover) show(p)
colour=['#ff7f0e','#2ca02c','#d62728','#1f77b4'] #output_file("test1.html") p = figure(x_axis_label='Time', y_axis_label=selected_features,x_axis_type='datetime',title=selected_node, plot_width=700, plot_height=400) p.line('time','count',source=source1,line_width=2, color=str(colour[0]),legend_label=str(df5.iloc[1,0])) p.line('time','count',source=source2,line_width=2, color=str(colour[1]),legend_label=str(df6.iloc[1,0])) p.line('time','count',source=source3,line_width=4, color=str(colour[2]),legend_label=str(df7.iloc[1,0])) else: pass p.legend.click_policy="hide" # add a hover tool and show the date in date time format hover = HoverTool(mode='mouse') hover.tooltips=[ ('Date', '@date{%F}'), ('Time', '@time{%H:%M}'), ('Count', '@count'), #('(x,y)', '($x, $y)') ] hover.formatters = {'@date': 'datetime','@time': 'datetime'} p.add_tools(hover) ##show the chart st.write('Chart:') st.write(selected_features, 'of', selected_node) st.bokeh_chart(p) st.button("Re-run")
def scatter(status, furthest): #Check if furthest points is selected and get correct data if furthest == 'True': with open('status_times_furthest_condensed.csv', 'wb') as f: s3.download_fileobj(s3_bucket, 'status_times_furthest_condensed.csv', f) df = pd.read_csv('status_times_furthest_condensed.csv', sep="|") else: with open('status_times_condensed.csv', 'wb') as f: s3.download_fileobj(s3_bucket, 'status_times_condensed.csv', f) df = pd.read_csv('status_times_condensed.csv', sep="|") df['Ship Date'] = pd.to_datetime(df['Ship Date']) df[status] = pd.to_numeric(df[status], downcast="float") source = ColumnDataSource(df) p = figure(x_axis_type='datetime', plot_width=1200, plot_height=400, title=f'{status}', y_axis_label='Hours', tools="pan,box_select,zoom_in,zoom_out,save,reset") p.scatter( y=status, x='Ship Date', # fill_color = factor_cmap( # 'Car', # palette=Blues8, # factors=car_list # ), fill_alpha=0.5, source=source, ) #Custom html hover box for individual points on scatter plot hover = HoverTool() html = """ <div> <h4>@Story</h4> <div><strong>Ship Date: </strong>@{Ship Date}{%F}</div> <div><strong>Hours: </strong>@{$status}{%0.2f}</div> </div> """ replaced_html = Template(html).safe_substitute(status=status) hover.tooltips = replaced_html hover.formatters = { "@{Ship Date}": "datetime", f"@\u007b{status}\u007d": "printf", } p.add_tools(hover) save(p) #Send back js and html script, div = components(p) return script, div