def plot_setter(df, ticker): p = figure(width=700, height=400, title="Ticker=" + ticker, tools="") hover = HoverTool(tooltips=[ ('date', '@date{%F}'), ('close', '$@close{%0.2f}'), ], formatters={ 'date': 'datetime', 'close': 'printf' }) hover.mode = 'vline' hover.line_policy = 'nearest' p.add_tools(hover) dfcds = ColumnDataSource(df) p.line('date', 'close', source=dfcds, color="#000000") p.xaxis.formatter = DatetimeTickFormatter(days=["%d %b"]) p.x_range = Range1d(df['date'].min(), df['date'].max()) p.toolbar.logo = None p.toolbar_location = None p.title.text_color = "#000000" p.title.text_font_size = "1.5em" p.axis.major_label_text_color = "#000000" p.axis.major_label_text_font_size = "1.25em" p.xgrid.grid_line_color = None p.ygrid.grid_line_alpha = 0.5 p.ygrid.grid_line_dash = [2, 4] p.outline_line_color = None p.yaxis.axis_label = "Close" return p
def make_plot(src, p): journal = ["AA", "ASR", "JMAS"] palette = [cc.rainbow[i * 15] for i in range(17)] p.vbar(x='x', top='counts', width=0.9, source=src, fill_color=factor_cmap('x', palette=palette, factors=journal, start=1, end=2)) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None hover = HoverTool() hover.tooltips = [("count", "@counts")] hover.mode = 'vline' p.add_tools(hover) # Styling p = style(p) return p
def plot_bokeh(df, ticker): p = figure(width=800, height=400, title=ticker.upper(), tools="") hover = HoverTool(tooltips=""" <div> <table> <tr><td class="ttlab">Date:</td><td>@date_str</td></tr> <tr><td class="ttlab">Close:</td><td>@close_str</td></tr> </table> </div> """) hover.mode = 'vline' hover.line_policy = 'nearest' p.add_tools(hover) crosshair = CrosshairTool() crosshair.dimensions = 'height' crosshair.line_color = "#ffffff" p.add_tools(crosshair) dfcds = ColumnDataSource(df) p.line('date', 'close', source=dfcds, color="#44ddaa") p.xaxis.formatter = DatetimeTickFormatter(days=["%d %b"]) p.x_range = Range1d(df['date'].min(), df['date'].max()) p.toolbar.logo = None p.toolbar_location = None return p
def make_plot(df): #Make the plot, save on .HTML file fig = figure(x_axis_label='Date', y_axis_label='Price', x_axis_type='datetime', plot_width=1024, plot_height=768) #datetime formatted_date = [] date = df['datetime'].tolist() for f in date: formatted_date.append(datetime.strptime(f, "%Y-%m-%d %H:%M:%S")) #Making the source source = ColumnDataSource( data={ 'price': df['daiusd_price'].tolist(), 'date': formatted_date, 'price_selling': df['daiusd_selling'].tolist(), 'price_purchase': df['daiusd_purchase'].tolist() }) #Drawing the lines fig.line(x='date', y='price', line_width=3, color='red', source=source, legend_label='DAI/USD price') fig.line(x='date', y='price_selling', line_width=3, color='blue', source=source, legend_label='DAI/USD selling price') fig.line(x='date', y='price_purchase', line_width=3, color='green', source=source, legend_label='DAI/USD purchase price') #Configuring hovers hover = HoverTool() hover.tooltips = [('DAI price', '$@{price}{%0.2f}'), ('Date', '@date{%F}'), ('DAI selling price', '$@{price_selling}{%0.2f}'), ('DAI purchase price', '$@{price_purchase}{%0.2f}')] hover.mode = 'vline' hover.formatters = { '@{price}': 'printf', '@date': 'datetime', '@{price_selling}': 'printf', '@{price_purchase}': 'printf' } #Quiting toolbar fig.toolbar_location = None #Adding hovers fig.add_tools(hover) #Save save(obj=fig, title='Dai price - Beta')
def _create_hover(tooltips=[('date', '$x{%F}'), ('value', '@y{0.000}')], formatters={'$x': 'datetime'}, mode='vline', **kwargs): hover = HoverTool(**kwargs) hover.tooltips = tooltips hover.formatters = formatters hover.mode = mode return hover
def plot_bokeh_events(src, plot=None, pitch_colour='green', event_hover=True): from bokeh.models import Arrow, OpenHead, LabelSet, HoverTool, Segment import Football_Pitch_Bokeh as fpbokeh line_colour = 'white' if pitch_colour == 'white': line_colour = 'black' if plot is None: p = fpbokeh.draw_pitch(hspan=[-53, 53], vspan=[-34, 34], fill_color=pitch_colour, line_color=line_colour) else: p = plot players = p.circle(source=src, x='Start X', y='Start Y', color='red', size=10, alpha=0.7) glyph = Segment(x0="Start X", y0="Start Y", x1="End X", y1="End Y", line_color="black", line_width=1) p.add_glyph(src, glyph) p.add_layout( LabelSet(x='Start X', y='Start Y', x_offset=3, y_offset=3, text='Shirt Number', text_font_size='10pt', text_color='red', source=src, level='glyph')) if event_hover == True: hover = HoverTool() hover.mode = 'mouse' hover.tooltips = [("Event", "@play_frame"), ("Player", "@{Shirt Number}"), ("Type", "@Type"), ("SubType", "@SubType"), ("(Start X,Start Y)", "($x, $y)")] hover.renderers = [players] p.add_tools(hover) return p
def bokehplot(df_1, ticker): """Create a time-series line plot in Bokeh.""" p = figure(width=600, height=300, title=ticker.upper(), tools="") hover = HoverTool(tooltips=""" <div> <table> <tr><td class="ttlab">Date:</td><td>@date_str</td></tr> <tr><td class="ttlab">Close:</td><td>@close</td></tr> </table> </div> """) hover.mode = 'vline' hover.line_policy = 'nearest' p.add_tools(hover) crosshair = CrosshairTool() crosshair.dimensions = 'height' crosshair.line_color = "#ffffff" p.add_tools(crosshair) dfcds = ColumnDataSource(df_1) p.line('date', 'close', source=dfcds, color="#44ddaa") p.xaxis.formatter = DatetimeTickFormatter(days=["%d %b"]) p.x_range = Range1d(df_1['date'].min(), df_1['date'].max()) p.toolbar.logo = None p.toolbar_location = None # Style plot p.background_fill_color = "#234567" p.border_fill_color = "#234567" p.title.text_color = "#ffffff" p.title.text_font_size = "1.25em" p.axis.major_label_text_color = "#ffffff" p.axis.major_label_text_font_size = "0.875em" p.axis.axis_line_color = "#ffffff" p.axis.major_tick_line_color = "#ffffff" p.axis.minor_tick_line_color = "#ffffff" p.xgrid.grid_line_color = None p.ygrid.grid_line_alpha = 0.5 p.ygrid.grid_line_dash = [4, 6] p.outline_line_color = None p.yaxis.axis_label = "Closing price" p.yaxis.axis_label_text_color = "#ffffff" p.yaxis.axis_label_text_font_size = "1em" p.yaxis.axis_label_text_font_style = "normal" p.yaxis.axis_label_standoff = 12 return p
def plot_bokeh_surface_at_event(event_src, att_src, def_src, ball_src, surface_src, bokeh_attack, bokeh_defence, xgrid, ygrid, field_dimen=( 106., 68., ), new_grid_size=500, point_click=False): import matplotlib as plt import matplotlib.cm as cm import numpy as np from bokeh.models import ColumnDataSource, HoverTool, BooleanFilter, CDSView, LabelSet, PointDrawTool, Tabs colormap = cm.get_cmap("bwr") bokehpalette = [ plt.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N)) ] p = plot_bokeh_frame(att_src, def_src, ball_src, pitch_colour='white', edit=point_click, tracking_hover=False) p = plot_bokeh_events(event_src, p, pitch_colour='white') surface = p.image(source=surface_src, image='image', x='x', y='y', dw='dw', dh='dh', palette=bokehpalette, level="image") hover = HoverTool() hover.mode = 'mouse' hover.tooltips = [("Value", "@image"), ("(x,y)", "($x, $y)")] hover.renderers = [surface] p.add_tools(hover) return p
def plot_ticker(ticker): # Retrieve and process data: url = urlhead + ticker + urltail page = requests.get(url) json = page.json() df = pd.DataFrame(json['Time Series (Daily)']) # New DataFrame to append values: df_1 = pd.DataFrame() close = np.asarray(df.iloc[3]) df_1['date'] = pd.to_datetime(list(df)) df_1['close'] = close # Last 30 days: df_1 = df_1[0:30] # Create a new column with dates as string: df_1['date_str'] = df_1['date'].map(lambda x: x.strftime("%Y-%m-%d")) dfcds = ColumnDataSource(df_1) # Create Bokeh plot: p = figure(width=600, height=300, title=ticker.upper(), tools="") hover = HoverTool(tooltips = [ ('Date', '@date_str'), ('Close', '@close')]) hover.mode = 'vline' hover.line_policy = 'nearest' p.add_tools(hover) crosshair = CrosshairTool() crosshair.dimensions = 'height' p.add_tools(crosshair) p.line('date', 'close', source = dfcds) p.xaxis.formatter=DatetimeTickFormatter(days=["%d %b"]) p.x_range=Range1d(df_1['date'].min(), df_1['date'].max()) p.toolbar.logo = None p.toolbar_location = None return p
#print(f"CDS Keys::\n{source.data.keys}") # supposed to show the col-keys as 'flights','left','right','index' # new way of referencing COLS directly by STRINGS # add quad glype, w/ SOURCE p.quad(source=source, bottom=0, top='flights', left='left', right='right', fill_color='red', line_color='black') # pass hovertool-obj a list of TOOLTIPS as <tuple>s # tuple -- (label-for-data, spec-data-to-focus-on) # '@' for pointat our data ... '$' for posit on graph # or hov = HoverTool() -\n- hov.tooltips= ... hov = HoverTool(tooltips=[ ('Delay Interval Left', '@left'), #'Delay', '@f_interval' ('(x, y)', '($x, $y)') ]) # 'Nun of Flights', '@f_flights' ## # Add a column showing the extent of each interval # not well explained ##delays['f_interval'] = ['%d to %d minutes' % (left, right) ## for left, right in zip(delays['left'], delays['right'])] hov.mode = "vline" p.add_tools(hov) show(p)
def show_model_performance_plot(hist_prices, y_test_pred, y_test_real, dates, split_frac=0.95): """ Function returns the model predicted prices over the test set in LSTM model :param hist_prices: pd.DataFrame - Historical Prices of the stock :param y_test_pred: np.array - predicted prices from LSTM model returned by utils.test_LSTM_model :param y_test_real: np.array - Empirical prices over the same time period returned by utils.test_LSTM_model :param dates: np.array - dates over which the model was tested on :param split_frac: np.float64 - the fraction used to do the train test split in utils.get_train_test_data() :returns: Bokeh.line - Bokeh plot with 2 lines - predicted prices and real prices """ n = int(split_frac * hist_prices.shape[0]) dates = hist_prices[n - 1:].reset_index().iloc[:, [0]] #get recent dates real = pd.DataFrame(y_test_real, columns=["real"]) pred = pd.DataFrame(y_test_pred, columns=["pred"]) plot_frame = pd.concat([real, pred], axis=1) plot_frame = pd.concat([plot_frame, dates], axis=1) plot_frame["Date"] = pd.to_datetime(plot_frame['Date']) source = ColumnDataSource(plot_frame) p = figure(x_axis_type='datetime', height=200, tools="reset, save, wheel_zoom, pan") p.sizing_mode = "scale_width" p.grid.grid_line_alpha = 0 p.yaxis.minor_tick_line_color = None p.yaxis.formatter = NumeralTickFormatter(format="$0,0") p.line(x='Date', y='real', line_width=1, source=source, legend_label='Real Prices', color="#7564ff") p.line(x='Date', y='pred', line_width=1, source=source, legend_label='Predicted Prices', color="#1ae0ff") p.yaxis.axis_label = 'Prices' # hover tool tips hover = HoverTool(tooltips=[("Date", "@Date{%F}"), ("Real Price", "$@real"), ("Predicted Price", "$@pred")], formatters={"@Date": "datetime"}) hover.mode = 'vline' p.add_tools(hover) p.legend.location = "top_left" return p
def bokeh_patch(self, position, check_sld, bk_ax): """Shaft element patch. Patch that will be used to draw the shaft element. Parameters ---------- position : float Position in which the patch will be drawn. check_sld : bool If True, HoverTool displays only the slenderness ratio and color the elements in yellow if slenderness ratio < 1.6 bk_ax : bokeh plotting axes, optional Axes in which the plot will be drawn. Returns ------- hover : Bokeh HoverTool Bokeh HoverTool axes """ if check_sld is True and self.slenderness_ratio < 1.6: bk_color = "yellow" legend = "Shaft - Slenderness Ratio < 1.6" else: bk_color = self.material.color legend = "Shaft" # bokeh plot - plot the shaft z_upper = [position, position, position + self.L, position + self.L] y_upper = [self.idl / 2, self.odl / 2, self.odr / 2, self.idr / 2] z_lower = [position, position, position + self.L, position + self.L] y_lower = [-self.idl / 2, -self.odl / 2, -self.odr / 2, -self.idr / 2] source = ColumnDataSource( dict( z_l=[z_lower], y_l=[y_lower], z_u=[z_upper], y_u=[y_upper], sld=[self.slenderness_ratio], elnum=[self.n], out_d_l=[self.odl], out_d_r=[self.odr], in_d_l=[self.idl], in_d_r=[self.idr], length=[self.L], mat=[self.material.name], ) ) bk_ax.patches( xs="z_u", ys="y_u", source=source, line_color=bokeh_colors[0], line_width=1, fill_alpha=0.5, fill_color=bk_color, legend_label=legend, name="u_shaft", ) bk_ax.patches( xs="z_l", ys="y_l", source=source, line_color=bokeh_colors[0], line_width=1, fill_alpha=0.5, fill_color=bk_color, legend_label=legend, name="l_shaft", ) hover = HoverTool(names=["l_shaft", "u_shaft"]) if check_sld: hover.tooltips = [ ("Element Number :", "@elnum"), ("Slenderness Ratio :", "@sld"), ] else: hover.tooltips = [ ("Element Number :", "@elnum"), ("Left Outer Diameter :", "@out_d_l"), ("Left Inner Diameter :", "@in_d_l"), ("Right Outer Diameter :", "@out_d_r"), ("Right Inner Diameter :", "@in_d_r"), ("Element Length :", "@length"), ("Material :", "@mat"), ] hover.mode = "mouse" return hover
def bokeh_patch(self, position, length, bk_ax): """Disk element patch. Patch that will be used to draw the disk element. Parameters ---------- ax : matplotlib axes, optional Axes in which the plot will be drawn. bk_ax : bokeh plotting axes, optional Axes in which the plot will be drawn. position : float Position in which the patch will be drawn. length : float minimum length of shaft elements Returns ------- bk_ax : bokeh plotting axes Returns the axes object with the plot. """ zpos, ypos = position le = length / 8 # bokeh plot - coordinates to plot disks elements z_upper = [zpos, zpos + le, zpos - le] y_upper = [ypos, ypos * 4, ypos * 4] z_lower = [zpos, zpos + le, zpos - le] y_lower = [-ypos, -ypos * 4, -ypos * 4] source = ColumnDataSource( dict(z_l=z_lower, y_l=y_lower, z_u=z_upper, y_u=y_upper)) source_c = ColumnDataSource( dict( z_circle=[z_upper[0]], yu_circle=[y_upper[1]], yl_circle=[-y_upper[1]], radius=[le], elnum=[self.n], IP=[self.Ip], ID=[self.Id], mass=[self.m], )) bk_ax.patch( x="z_u", y="y_u", source=source, alpha=1, line_width=2, color=bokeh_colors[9], legend="Disk", ) bk_ax.patch( x="z_l", y="y_l", source=source, alpha=1, line_width=2, color=bokeh_colors[9], ) bk_ax.circle( x="z_circle", y="yu_circle", radius="radius", source=source_c, fill_alpha=1, color=bokeh_colors[9], name="uc_disk", ) bk_ax.circle( x="z_circle", y="yl_circle", radius="radius", source=source_c, fill_alpha=1, color=bokeh_colors[9], name="lc_disk", ) hover = HoverTool(names=["uc_disk", "lc_disk"]) hover.tooltips = [ ("Disk Node :", "@elnum"), ("Polar Moment of Inertia :", "@IP"), ("Diametral Moment of Inertia :", "@ID"), ("Disk mass :", "@mass"), ] hover.mode = "mouse" if len(bk_ax.hover) == 1: bk_ax.add_tools(hover)
def write_and_plot(sample_dict, path): CSV_PATH, PLOT_PATH, RAW_CSV_DATA = get_output(path) # Merge all the sample data sample_families = list(sample_dict.keys()) composite_data = vivdict() integral_data = [] VOLUME = 1.2 VOLUME_CALCULATED = VOLUME / (60 * 1000) for family in sample_families: for method, _ in sample_dict[family].items(): log.info(f"Working on {method}") composite_data[family][method] = cd = pd.concat( sample_dict[family][method], axis=1 ).apply(lambda g: pd.Series.interpolate(g, method="cubic")) ppm_calculated_once = cd.mul(10000 * 1.9378).droplevel(axis=1, level=1) # Integral ppm = pd.DataFrame(ppm_calculated_once[0:150]) ppm.reset_index(inplace=True) ppm["Volume"] = ppm["Time"].apply(lambda x: x * VOLUME_CALCULATED) ppm.set_index("Volume", inplace=True) ppm = ppm.drop(columns=["Time"], errors="ignore") row_integral = ( ppm.ewm(span=5) .mean() .apply(lambda g: integrate.trapz(x=g.index, y=g.values)) ) row_integral_std = row_integral.std() integral = pd.DataFrame( {"Integral": row_integral.mean(), "STD": row_integral_std}, index=[f"{family}_{method}"], ) integral["lower"] = row_integral.mean() - row_integral_std integral["upper"] = row_integral.mean() + row_integral_std integral_data.append(integral) # Mean Data cd_mean = cd.mean(axis=1).reset_index() cd_mean.columns = ["Time", "CO2"] cd_mean.to_csv( os.path.join(CSV_PATH, f"{family}_{method}.csv"), sep=",", index=False ) # Mean/STD Data source_data = pd.DataFrame() source_data["mean"] = ppm_calculated_once.mean(axis=1) source_data["std"] = ppm_calculated_once.std(axis=1) source_data["lower"] = source_data["mean"] - source_data["std"] source_data["upper"] = source_data["mean"] + source_data["std"] # Graphing our data output_file(os.path.join(PLOT_PATH, f"{family}-{method}.html")) source_data = source_data.reset_index().rename(columns={"index": "Time"}) source = ColumnDataSource(source_data) p = figure( title=f"{family} {method}", x_axis_label="Time", y_axis_label="CO2 Release", background_fill_color="#efefef", toolbar_location=None, ) p.line( source=source, x="Time", y="mean", ) band = Band( base="Time", lower="lower", upper="upper", source=source, level="underlay", fill_alpha=1.0, line_width=1, line_color="black", ) p.add_layout(band) p.title.text = f"{family} {method}" p.xgrid[0].grid_line_color = None p.ygrid[0].grid_line_alpha = 0.5 p.xaxis.axis_label = "Time" p.yaxis.axis_label = "CO2 (PPM)" p.y_range.start = source_data["mean"].min() - source_data["std"].max() / 6 p.y_range.end = source_data["mean"].max() + source_data["std"].max() p.ygrid.band_fill_alpha = 0.1 p.ygrid.band_fill_color = "#C0C0C0" p.add_tools( HoverTool(tooltips=[("Value", "@mean"), ("STD", "@std")], mode="vline") ) show(p) integral_df = pd.concat(integral_data).reset_index() groups = integral_df["index"] output_file(os.path.join(PLOT_PATH, f"Integral Data.html")) source = ColumnDataSource(integral_df) p = figure( x_range=groups, toolbar_location=None, title="CO2 Integral", background_fill_color="#efefef", y_axis_label="CO2 (mg)", tools="tap", ) p.circle( x="index", y="Integral", color="red", fill_alpha=0.4, line_color="firebrick", line_alpha=1.0, size=10, source=source, selection_color="firebrick", nonselection_fill_alpha=0.2, nonselection_fill_color="firebrick", nonselection_line_color="blue", nonselection_line_alpha=1.0, ) p.add_layout( Whisker( source=source, base="index", upper="upper", lower="lower", level="overlay" ) ) p.xaxis.major_label_orientation = "vertical" p.y_range.start = integral_df["Integral"].min() - integral_df["STD"].max() * 1.2 p.y_range.end = integral_df["Integral"].max() + integral_df["STD"].max() * 1.2 hover = HoverTool() hover.tooltips = [("Sample", "@index"), ("Value", "@Integral"), ("STD", "@STD")] hover.mode = "vline" p.add_tools(hover) show(p)
def show_portfolio_future_plot(gbm_sim, init_cap, days_sim, hist_data): """ Returns the plot of possible future projections from gbm_sim, at the 5%, 50%, 95% confidence :param gbm_sim: pd.DataFrame - simulation results from utils.simulate_gbm() :param init_cap: np.float64 - initial capital :param days_sim: int - number of days to simulate :param hist_data: pd.DataFrame - the historical prices (to get the last day of data) :returns: Bokeh.line - 3 Lines outlining the % chance of getting above certain values """ if gbm_sim is not None: last_day = hist_data.index.max() dates = [last_day + timedelta(days=i) for i in range(days_sim)] sim_res = get_sim_results_stats(gbm_sim) bottom = sim_res.filter(['net_asset_change']).quantile(.05) / len( gbm_sim) #arithmetic average daily returns middle = sim_res.filter(['net_asset_change' ]).quantile(.5) / len(gbm_sim) top = sim_res.filter(['net_asset_change']).quantile(.95) / len(gbm_sim) # print(bottom) bottom_ind_value = init_cap * np.cumprod([1 + bottom] * days_sim) middle_ind_value = init_cap * np.cumprod([1 + middle] * days_sim) top_ind_value = init_cap * np.cumprod([1 + top] * days_sim) ind_value = pd.DataFrame( data={ "bottom_ind_value": bottom_ind_value, "middle_ind_value": middle_ind_value, "top_ind_value": top_ind_value }) ind_value['dates'] = dates source = ColumnDataSource(ind_value) plot_proj = figure(x_axis_type='datetime', height=250, tools="reset, save, wheel_zoom, pan") plot_proj.sizing_mode = "scale_width" plot_proj.grid.grid_line_alpha = 0 plot_proj.xaxis.axis_label = 'Date' plot_proj.yaxis.axis_label = 'Indicative Value' plot_proj.ygrid.band_fill_color = None plot_proj.ygrid.band_fill_alpha = 0 plot_proj.yaxis.formatter = NumeralTickFormatter(format="$0,0") plot_proj.xaxis.minor_tick_line_color = None plot_proj.line(x="dates", y="bottom_ind_value", color='#006565', source=source, legend_label='5th Percentile', line_width=1.5) r1 = plot_proj.line(x="dates", y="middle_ind_value", color='#008c8c', source=source, legend_label='50th Percentile', line_width=1.5) plot_proj.line(x="dates", y="top_ind_value", color='#00eeee', source=source, legend_label='95% Percentile', line_width=1.5) hover = HoverTool(tooltips=[ ('Date', '@dates{%F}'), ("Projected Value, 5% chance of having more than", '$@top_ind_value{0,0.00}'), ("Projected Value, 50% chance of having more than", '$@middle_ind_value{0,0.00}'), ("Projected Value, 95% chance of having more than", '$@bottom_ind_value{0,0.00}') ], formatters={"@dates": "datetime"}) hover.renderers = [r1] hover.mode = 'vline' plot_proj.add_tools(hover) plot_proj.legend.location = "top_left" return plot_proj
source=source, color=plot_info[gage]['color'], alpha=1.0, line_dash=plot_info[gage]['bokeh_style']) myLegendList.append((label_sting, [l])) circle = s1.circle('dateX', 'v', source=source, size=6, color=plot_info[gage]['color'], alpha=0.0) hover = s1.select(dict(type=HoverTool)) hover.tooltips = [("site", "@site"), ("date", "@dateX_str"), ("value", "@v")] hover.mode = 'mouse' legend = Legend(items=myLegendList, location=(40, 0)) s1.add_layout(legend, 'above') s1.legend.orientation = "horizontal" #TDG plot dates = gage_lists['Qtotal']["dates_bokeh_TZbug"] dates2 = gage_lists['Qtotal']["dates_bokeh_TZbug"] gage_lists['TDG115'] = { 'dates_bokeh_TZbug': dates2, 'meas': [115] * len(dates), 'dates': dates } gage_lists['TDG120'] = {
def assembly_chart(df, complements): """function to assembly the chart""" print('starting the plot...') # specify the output file name output_file("movigrama_chart.html") # force to show only one plot when multiples executions of the code occur # otherwise the plots will append each time one new calling is done reset_output() # create ColumnDataSource objects directly from Pandas data frames source = ColumnDataSource(df) # use the column DT as index df.set_index('DT', inplace=True) ########################################################################### # # Movigrama Plot # ########################################################################### # build figure of the plot p = figure(x_axis_type='datetime', x_axis_label='days of moviment', y_axis_label='unities movimented', plot_width=1230, plot_height=500, active_scroll='wheel_zoom') # TODO Specify X range (not all plots have 365 days of moviment) # build the Stock Level bar r1 = p.vbar(x='DT', bottom=0, top='STOCK', width=pd.Timedelta(days=1), fill_alpha=0.4, color='paleturquoise', source=source) # build the OUT bar p.vbar(x='DT', bottom=0, top='SOMA_SAI', width=pd.Timedelta(days=1), fill_alpha=0.8, color='crimson', source=source) # build the IN bar p.vbar(x='DT', bottom=0, top='SOMA_ENTRA', width=pd.Timedelta(days=1), fill_alpha=0.8, color='seagreen', source=source) # edit title # adds warehouse title p.add_layout( Title(text=complements['warehouse'], text_font='helvetica', text_font_size='10pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="italic"), 'above') # adds product title p.add_layout( Title(text=complements['product'], text_font='helvetica', text_font_size='10pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="italic"), 'above') # adds main title p.add_layout( Title(text='Movigrama Endicon', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.9, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p.renderers.extend([hline]) # adapt the range to the plot p.x_range.range_padding = 0.1 p.y_range.range_padding = 0.1 # format the plot's outline p.outline_line_width = 4 p.outline_line_alpha = 0.1 p.outline_line_color = 'orangered' # format major labels p.axis.major_label_text_color = 'gray' p.axis.major_label_text_font_style = 'bold' # format labels p.axis.axis_label_text_color = 'gray' p.axis.axis_label_text_font_style = 'bold' # p.xgrid.grid_line_color = None # disable vertical bars # p.ygrid.grid_line_color = None # disable horizontal bars # change placement of minor and major ticks in the plot p.axis.major_tick_out = 10 p.axis.minor_tick_in = -3 p.axis.minor_tick_out = 6 p.axis.minor_tick_line_color = 'gray' # format properly the X datetime axis p.xaxis.formatter = DatetimeTickFormatter(days=['%d/%m'], months=['%m/%Y'], years=['%Y']) # iniciate hover object hover = HoverTool() hover.mode = "vline" # activate hover by vertical line hover.tooltips = [("SUM-IN", "@SOMA_ENTRA"), ("SUM-OUT", "@SOMA_SAI"), ("COUNT-IN", "@TRANSACT_ENTRA"), ("COUNT-OUT", "@TRANSACT_SAI"), ("STOCK", "@STOCK"), ("DT", "@DT{%d/%m/%Y}")] # use 'datetime' formatter for 'DT' field hover.formatters = {"DT": 'datetime'} hover.renderers = [r1] # display tolltip only to one render p.add_tools(hover) ########################################################################### # # Demand analysis # ########################################################################### # change to positive values df['out_invert'] = df['SOMA_SAI'] * -1 # moving average with n=30 days df['MA30'] = df['out_invert'].rolling(30).mean().round(0) # moving standard deviation with n=30 days df['MA30_std'] = df['out_invert'].rolling(30).std().round(0) # lower control limit for 1 sigma deviation df['lcl_1sigma'] = (df['MA30'] - df['MA30_std']) # upper control limit for 1 sigma deviation df['ucl_1sigma'] = (df['MA30'] + df['MA30_std']) source = ColumnDataSource(df) p1 = figure(plot_width=1230, plot_height=500, x_range=p.x_range, x_axis_type="datetime", active_scroll='wheel_zoom') # build the Sum_out bar r1 = p1.vbar(x='DT', top='out_invert', width=pd.Timedelta(days=1), color='darkred', line_color='salmon', fill_alpha=0.4, source=source) # build the moving average line p1.line(x='DT', y='MA30', source=source) # build the confidence interval band = Band(base='DT', lower='lcl_1sigma', upper='ucl_1sigma', source=source, level='underlay', fill_alpha=1.0, line_width=1, line_color='black') p1.renderers.extend([band]) # adds title p1.add_layout( Title(text='Demand Variability', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p1.renderers.extend([hline]) # format the plot's outline p1.outline_line_width = 4 p1.outline_line_alpha = 0.1 p1.outline_line_color = 'orangered' # format major labels p1.axis.major_label_text_color = 'gray' p1.axis.major_label_text_font_style = 'bold' # format labels p1.axis.axis_label_text_color = 'gray' p1.axis.axis_label_text_font_style = 'bold' # change placement of minor and major ticks in the plot p1.axis.major_tick_out = 10 p1.axis.minor_tick_in = -3 p1.axis.minor_tick_out = 6 p1.axis.minor_tick_line_color = 'gray' # format properly the X datetime axis p1.xaxis.formatter = DatetimeTickFormatter(days=['%d/%m'], months=['%m/%Y'], years=['%Y']) # iniciate hover object hover = HoverTool() hover.mode = "vline" # activate hover by vertical line hover.tooltips = [("DEMAND", '@out_invert'), ("UCL 1σ", "@ucl_1sigma"), ("LCL 1σ", "@lcl_1sigma"), ("M AVG 30d", "@MA30"), ("DT", "@DT{%d/%m/%Y}")] # use 'datetime' formatter for 'DT' field hover.formatters = {"DT": 'datetime'} hover.renderers = [r1] # display tolltip only to one render p1.add_tools(hover) ########################################################################### # # Demand groupped by month # ########################################################################### resample_M = df.iloc[:, 0:6].resample('M').sum() # resample to month # create column date as string resample_M['date'] = resample_M.index.strftime('%b/%y').values # moving average with n=3 months resample_M['MA3'] = resample_M['out_invert'].rolling(3).mean() resample_M['MA3'] = np.ceil(resample_M.MA3) # round up the column MA3 # resample to month with mean resample_M['mean'] = np.ceil(resample_M['out_invert'].mean()) # resample to month with standard deviation resample_M['std'] = np.ceil(resample_M['out_invert'].std()) # moving standard deviation with n=30 days resample_M['MA3_std'] = np.ceil(resample_M['out_invert'].rolling(3).std()) # lower control limit for 1 sigma deviation resample_M['lcl_1sigma'] = resample_M['MA3'] - resample_M['MA3_std'] # upper control limit for 1 sigma deviation resample_M['ucl_1sigma'] = resample_M['MA3'] + resample_M['MA3_std'] source = ColumnDataSource(resample_M) p2 = figure(plot_width=1230, plot_height=500, x_range=FactorRange(factors=list(resample_M.date)), title='demand groupped by month') colors = factor_cmap('date', palette=Category20_20, factors=list(resample_M.date)) p2.vbar(x='date', top='out_invert', width=0.8, fill_color=colors, fill_alpha=0.8, source=source, legend=value('OUT')) p2.line(x='date', y='MA3', color='red', line_width=3, line_dash='dotted', source=source, legend=value('MA3')) p2.line(x='date', y='mean', color='blue', line_width=3, line_dash='dotted', source=source, legend=value('mean')) band = Band(base='date', lower='lcl_1sigma', upper='ucl_1sigma', source=source, level='underlay', fill_alpha=1.0, line_width=1, line_color='black') labels1 = LabelSet(x='date', y='MA3', text='MA3', level='glyph', y_offset=5, source=source, render_mode='canvas', text_font_size="8pt", text_color='darkred') labels2 = LabelSet(x='date', y='out_invert', text='out_invert', level='glyph', y_offset=5, source=source, render_mode='canvas', text_font_size="8pt", text_color='gray') low_box = BoxAnnotation( top=resample_M['mean'].iloc[0] - resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='red') mid_box = BoxAnnotation( bottom=resample_M['mean'].iloc[0] - resample_M['std'].iloc[0], # analysis:ignore top=resample_M['mean'].iloc[0] + resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='green') high_box = BoxAnnotation( bottom=resample_M['mean'].iloc[0] + resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='red') p2.renderers.extend([band, labels1, labels2, low_box, mid_box, high_box]) p2.legend.click_policy = "hide" p2.legend.background_fill_alpha = 0.4 p2.add_layout( Title(text='Demand Grouped by Month', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p2.renderers.extend([hline]) # format the plot's outline p2.outline_line_width = 4 p2.outline_line_alpha = 0.1 p2.outline_line_color = 'orangered' # format major labels p2.axis.major_label_text_color = 'gray' p2.axis.major_label_text_font_style = 'bold' # format labels p2.axis.axis_label_text_color = 'gray' p2.axis.axis_label_text_font_style = 'bold' # change placement of minor and major ticks in the plot p2.axis.major_tick_out = 10 p2.axis.minor_tick_in = -3 p2.axis.minor_tick_out = 6 p2.axis.minor_tick_line_color = 'gray' # iniciate hover object # TODO develop hoverTool # hover = HoverTool() # hover.mode = "vline" # activate hover by vertical line # hover.tooltips = [("SUM-IN", "@SOMA_ENTRA"), # ("SUM-OUT", "@SOMA_SAI"), # ("COUNT-IN", "@TRANSACT_ENTRA"), # ("COUNT-OUT", "@TRANSACT_SAI"), # ("STOCK", "@STOCK")] # hover.renderers = [r1] # display tolltip only to one render # p2.add_tools(hover) ########################################################################### # # Plot figures # ########################################################################### # put the results in a column and show show(column(p, p1, p2)) # show(p) # plot action print('plot finished')
def bokeh_patch(self, position, SR, bk_ax): """Shaft element patch. Patch that will be used to draw the shaft element. Parameters ---------- bk_ax : bokeh plotting axes, optional Axes in which the plot will be drawn. position : float Position in which the patch will be drawn. Returns ------- """ if self.n in SR: bk_color = "yellow" legend = "Shaft - Slenderness Ratio < 1.6" else: bk_color = bokeh_colors[2] legend = "Shaft" source_u = ColumnDataSource( dict( top=[self.o_d / 2], bottom=[self.i_d / 2], left=[position], right=[position + self.L], elnum=[self.n], out_d=[self.o_d], in_d=[self.i_d], length=[self.L], mat=[self.material.name], )) source_l = ColumnDataSource( dict( top=[-self.o_d / 2], bottom=[-self.i_d / 2], left=[position], right=[position + self.L], elnum=[self.n], out_d=[self.o_d], in_d=[self.i_d], length=[self.L], mat=[self.material.name], )) # bokeh plot - plot the shaft bk_ax.quad( top="top", bottom="bottom", left="left", right="right", source=source_u, line_color=bokeh_colors[0], line_width=1, fill_alpha=0.5, fill_color=bk_color, legend=legend, name="u_shaft", ) bk_ax.quad( top="top", bottom="bottom", left="left", right="right", source=source_l, line_color=bokeh_colors[0], line_width=1, fill_alpha=0.5, fill_color=bk_color, name="l_shaft", ) hover = HoverTool(names=["u_shaft", "l_shaft"]) hover.tooltips = [ ("Element Number :", "@elnum"), ("Outer Diameter :", "@out_d"), ("Internal Diameter :", "@in_d"), ("Element Length :", "@length"), ("Material :", "@mat"), ] hover.mode = "mouse" if len(bk_ax.hover) == 0: bk_ax.add_tools(hover)
def bokeh_patch(self, position, bk_ax, **kwargs): """Point mass element patch. Patch that will be used to draw the point mass element. Parameters ---------- bk_ax : bokeh plotting axes, optional Axes in which the plot will be drawn. position : float Position in which the patch will be drawn. kwargs : optional Additional key word arguments can be passed to change the plot (e.g. linestyle='--') Returns ------- bk_ax : bokeh plotting axes Returns the axes object with the plot. """ zpos, ypos = position radius = ypos / 8 default_values = dict( line_width=2.0, line_color=bokeh_colors[0], fill_alpha=1.0, fill_color=bokeh_colors[7], legend_label="Point Mass", ) for k, v in default_values.items(): kwargs.setdefault(k, v) # bokeh plot - coordinates to plot point mass elements z_upper = [zpos] y_upper = [ypos] z_lower = [zpos] y_lower = [-ypos] source = ColumnDataSource( dict( z_l=z_lower, y_l=y_lower, z_u=z_upper, y_u=y_upper, elnum=[self.n], mx=[self.mx], my=[self.my], tag=[self.tag], )) bk_ax.circle( x="z_l", y="y_l", radius=radius, source=source, name="pmass_l", **kwargs, ) bk_ax.circle( x="z_u", y="y_u", radius=radius, source=source, name="pmass_u", **kwargs, ) hover = HoverTool(names=["pmass_l", "pmass_u"]) hover.tooltips = [ ("Point Mass Node :", "@elnum"), ("Mass (x) :", "@mx"), ("Mass (y) :", "@my"), ("Tag :", "@tag"), ] hover.mode = "mouse" return hover
def plot_bokeh_frame(att_src, def_src, ball_src, plot=None, pitch_colour='green', edit=False, tracking_hover=True): from bokeh.plotting import figure from bokeh.models import ColumnDataSource, HoverTool, BooleanFilter, CDSView, LabelSet, PointDrawTool from bokeh.io import output_notebook, show import Football_Pitch_Bokeh as fpbokeh line_colour = 'white' if pitch_colour == 'white': line_colour = 'black' if plot is None: p = fpbokeh.draw_pitch(hspan=[-53, 53], vspan=[-34, 34], fill_color=pitch_colour, line_color=line_colour) else: p = plot #attack patt = p.circle(x='x', y='y', source=att_src, color='red', alpha=0.7, size=10) #defence pdef = p.circle(x='x', y='y', source=def_src, color='blue', alpha=0.7, size=10) # ball pball = p.circle(x='x', y='y', source=ball_src, color='black', alpha=0.7, size=5) att_labels = LabelSet(x='x', y='y', x_offset=5, y_offset=5, text='Shirt Number', text_font_size="10pt", text_color='red', source=att_src) p.add_layout(att_labels) def_labels = LabelSet(x='x', y='y', x_offset=5, y_offset=5, text='Shirt Number', text_font_size="10pt", text_color='blue', source=def_src) p.add_layout(def_labels) if tracking_hover == True: hover = HoverTool() hover.mode = 'mouse' hover.tooltips = [ #("Player", "@{Shirt Number}"), ("(x,y)", "($x, $y)") ] hover.renderers = [patt, pdef, pball] p.add_tools(hover) if edit == True: point_draw_att = PointDrawTool() point_draw_att.renderers = [patt] point_draw_att.num_objects = 12 p.add_tools(point_draw_att) point_draw_def = PointDrawTool() point_draw_def.renderers = [pdef] point_draw_def.num_objects = 12 p.add_tools(point_draw_def) return p
def plotPeakResult(id_input, peakresult, outputfile="result.html"): """ Plots the peak results. Args: id_input (IdentificationInput): Identification input. peakresult (PeakResults): Peak result outputfile (str): The html file coontaining the plot """ energyScale = peakresult.getFit().energyScale centers = energyScale.getCenters() fit = peakresult.getFit().counts continuum = peakresult.getContinuum().counts hover = HoverTool() hover.mode = 'mouse' # activate hover by vertical line hover.tooltips = [("energy", "@energy"), ("intensity", "@intensity"), ("baseline", "@baseline"), ("width", "@width")] hover.renderers = [] panels = [] for axis_type in ["linear", "log"]: fig = figure(title="Peak Fitting Results", y_axis_type=axis_type, x_axis_label='Energy (keV)', y_axis_label='Counts') fig.varea(x=centers, y1=continuum, y2=fit, color="green", legend_label="peaks") for peak in peakresult.getPeaks(): ymax = fit[energyScale.findBin(peak.energy)] source = ColumnDataSource( data=dict(x=[peak.energy, peak.energy], y=[10e-10, ymax], energy=["%6.1f" % peak.energy] * 2, intensity=["%d" % peak.intensity] * 2, baseline=["%d" % peak.baseline] * 2, width=["%6.2f" % peak.width] * 2)) pline = fig.line('x', 'y', color="red", source=source) hover.renderers.append(pline) fig.add_tools(hover) fig.varea(x=centers, y1=np.ones(continuum.size) * 10e-10, y2=continuum, color="blue", legend_label="continuum") fig.line(centers, id_input.sample.counts, legend_label="sample", line_dash='dashed', color="black", line_width=2) panel = Panel(child=fig, title=axis_type) panels.append(panel) tabs = Tabs(tabs=panels) # add a line renderer with legend and line thickness # show the results output_file(outputfile) show(tabs)
def bokeh_patch(self, position, bk_ax): """Disk element patch. Patch that will be used to draw the disk element. Parameters ---------- bk_ax : bokeh plotting axes, optional Axes in which the plot will be drawn. position : float Position in which the patch will be drawn. Returns ------- bk_ax : bokeh plotting axes Returns the axes object with the plot. """ zpos, ypos = position step = ypos / 5 # bokeh plot - coordinates to plot disks elements z_upper = [zpos, zpos + step, zpos - step] y_upper = [ypos, ypos * 4, ypos * 4] z_lower = [zpos, zpos + step, zpos - step] y_lower = [-ypos, -ypos * 4, -ypos * 4] source = ColumnDataSource( dict( z_l=[z_lower], y_l=[y_lower], z_u=[z_upper], y_u=[y_upper], elnum=[self.n], IP=[self.Ip], ID=[self.Id], mass=[self.m], tag=[self.tag], )) source_c = ColumnDataSource( dict( z_circle=[z_upper[0]], yu_circle=[y_upper[1]], yl_circle=[-y_upper[1]], radius=[step], elnum=[self.n], IP=[self.Ip], ID=[self.Id], mass=[self.m], tag=[self.tag], )) bk_ax.patches( xs="z_u", ys="y_u", source=source, alpha=1, line_width=2, color=self.color, legend_label="Disk", name="ub_disk", ) bk_ax.patches( xs="z_l", ys="y_l", source=source, alpha=1, line_width=2, color=self.color, name="ub_disk", ) bk_ax.circle( x="z_circle", y="yu_circle", radius="radius", source=source_c, fill_alpha=1, color=self.color, name="uc_disk", ) bk_ax.circle( x="z_circle", y="yl_circle", radius="radius", source=source_c, fill_alpha=1, color=self.color, name="lc_disk", ) hover = HoverTool(names=["uc_disk", "lc_disk", "ub_disk", "lb_disk"]) hover.tooltips = [ ("Disk Node :", "@elnum"), ("Polar Moment of Inertia :", "@IP"), ("Diametral Moment of Inertia :", "@ID"), ("Disk mass :", "@mass"), ("Tag :", "@tag"), ] hover.mode = "mouse" return hover
def _plot_bokeh(self, harmonics=[1], **kwargs): wd = self.wd num_frequencies = wd.shape[1] log_dec = self.log_dec whirl = self.whirl_values speed_range = np.repeat( self.speed_range[:, np.newaxis], num_frequencies, axis=1 ) log_dec_map = log_dec.flatten() default_values = dict( cmap="viridis", vmin=min(log_dec_map), vmax=max(log_dec_map), s=30, alpha=1.0, ) for k, v in default_values.items(): kwargs.setdefault(k, v) camp = figure( tools="pan, box_zoom, wheel_zoom, reset, save", title="Campbell Diagram - Damped Natural Frequency Map", width=1600, height=900, x_axis_label="Rotor speed (rad/s)", y_axis_label="Damped natural frequencies (rad/s)", ) camp.xaxis.axis_label_text_font_size = "14pt" camp.yaxis.axis_label_text_font_size = "14pt" color_mapper = linear_cmap( field_name="color", palette=bp.viridis(256), low=min(log_dec_map), high=max(log_dec_map), ) for mark, whirl_dir, legend in zip( ["^", "o", "v"], [0.0, 0.5, 1.0], ["Foward", "Mixed", "Backward"] ): num_frequencies = wd.shape[1] for i in range(num_frequencies): w_i = wd[:, i] whirl_i = whirl[:, i] log_dec_i = log_dec[:, i] speed_range_i = speed_range[:, i] for harm in harmonics: camp.line( x=speed_range[:, 0], y=harm * speed_range[:, 0], line_width=3, color=bokeh_colors[0], line_dash="dotdash", line_alpha=0.75, legend="Rotor speed", muted_color=bokeh_colors[0], muted_alpha=0.2, ) idx = np.argwhere(np.diff(np.sign(w_i - harm*speed_range_i))).flatten() if len(idx) != 0: idx = idx[0] interpolated = interpolate.interp1d( x=[speed_range_i[idx], speed_range_i[idx+1]], y=[w_i[idx], w_i[idx+1]], kind="linear" ) xnew = np.linspace( speed_range_i[idx], speed_range_i[idx+1], num=30, endpoint=True, ) ynew = interpolated(xnew) idx = np.argwhere(np.diff(np.sign(ynew - harm*xnew))).flatten() source = ColumnDataSource( dict(xnew=xnew[idx], ynew=ynew[idx]) ) camp.square( "xnew", "ynew", source=source, size=10, color=bokeh_colors[9], name="critspeed" ) hover = HoverTool(names=["critspeed"]) hover.tooltips = [ ("Frequency :", "@xnew"), ("Critical Speed :", "@ynew") ] hover.mode = "mouse" whirl_mask = whirl_i == whirl_dir if whirl_mask.shape[0] == 0: continue else: source = ColumnDataSource( dict( x=speed_range_i[whirl_mask], y=w_i[whirl_mask], color=log_dec_i[whirl_mask], ) ) camp.scatter( x="x", y="y", color=color_mapper, marker=mark, fill_alpha=1.0, size=9, muted_color=color_mapper, muted_alpha=0.2, source=source, legend=legend, ) color_bar = ColorBar( color_mapper=color_mapper["transform"], width=8, location=(0, 0), title="log dec", title_text_font_style="bold italic", title_text_align="center", major_label_text_align="left", ) camp.add_tools(hover) camp.legend.background_fill_alpha = 0.1 camp.legend.click_policy = "mute" camp.legend.location = "top_left" camp.add_layout(color_bar, "right") return camp
sname = source.data['SCIENTIFIC_NAME'].tolist() # Specify the dimensions of the figure p = figure(plot_width=1500, plot_height=800, x_range=sname) # T2.3: Visualize the data using bokeh plot functions p.vbar(x='SCIENTIFIC_NAME', top='OBSERVATION_COUNT', source=source, width=0.7) # Add title and specify X and Y labels p.title.text = 'Birds Observation number based on their scientifc names' p.xaxis.axis_label = 'Scientific Name' p.yaxis.axis_label = 'Observation Number' p.y_range.start = 0 p.xgrid.grid_line_color = None p.xaxis.major_label_orientation = "vertical" p.outline_line_color = None # T2.2: Add the hovering tooltip hover = HoverTool() hover.tooltips = [('Observation count', '@OBSERVATION_COUNT')] hover.mode = 'vline' p.add_tools(hover) # T2.4: Save the plot using output_file # Create the output html file output_file('DVC_Exercise1_Task4.html') show(p)
def _cycle_info_plot_bokeh( cell, cycle=None, step=None, title=None, points=False, x=None, y=None, info_level=0, h_cycle=None, h_step=None, show_it=False, label_cycles=True, label_steps=False, **kwargs, ): """Plot raw data with annotations. This function uses Bokeh for plotting and is intended for use in Jupyter Notebooks. """ # TODO: check that correct new column-names are used # TODO: fix bokeh import from bokeh.io import output_notebook, show from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, LabelSet from bokeh.models import HoverTool from bokeh.models.annotations import Span from bokeh.models.widgets import Slider, TextInput from bokeh.plotting import figure output_notebook(hide_banner=True) if points: if cycle is None or (len(cycle) > 1): print( "Plotting points only allowed when plotting one single cycle.") print("Turning points off.") points = False if h_cycle is None: h_cycle = "cycle_index" # edit if h_step is None: h_step = "step_index" # edit if x is None: x = "test_time" # edit if y is None: y = "voltage" # edit if isinstance(x, tuple): x, x_label = x else: x_label = x if isinstance(y, tuple): y, y_label = y else: y_label = y t_x = x # used in generating title - replace with a selector t_y = y # used in generating title - replace with a selector if title is None: title = f"{t_y} vs. {t_x}" cols = [x, y] cols.extend([h_cycle, h_step]) df = cell.cell.raw.loc[:, cols] if cycle is not None: if not isinstance(cycle, (list, tuple)): cycle = [cycle] _df = df.loc[df[h_cycle].isin(cycle), :] if len(cycle) < 5: title += f" [c:{cycle}]" else: title += f" [c:{cycle[0]}..{cycle[-1]}]" if _df.empty: print(f"EMPTY (available cycles: {df[h_step].unique()})") return else: df = _df cycle = df[h_cycle].unique() if step is not None: if not isinstance(step, (list, tuple)): step = [step] _df = df.loc[df[h_step].isin(step), :] if len(step) < 5: title += f" (s:{step})" else: title += f" [s:{step[0]}..{step[-1]}]" if _df.empty: print(f"EMPTY (available steps: {df[h_step].unique()})") return else: df = _df x_min, x_max = df[x].min(), df[x].max() y_min, y_max = df[y].min(), df[y].max() if info_level > 0: table = cell.cell.steps df = _add_step_info_cols(df, table, cycle, step) source = ColumnDataSource(df) plot = figure( title=title, tools="pan,reset,save,wheel_zoom,box_zoom,undo,redo", x_range=[x_min, x_max], y_range=[y_min, y_max], **kwargs, ) plot.line(x, y, source=source, line_width=3, line_alpha=0.6) # labelling cycles if label_cycles: cycle_line_positions = [ df.loc[df[h_cycle] == c, x].min() for c in cycle ] cycle_line_positions.append(df.loc[df[h_cycle] == cycle[-1], x].max()) for m in cycle_line_positions: _s = Span( location=m, dimension="height", line_color="red", line_width=3, line_alpha=0.5, ) plot.add_layout(_s) s_y_pos = y_min + 0.9 * (y_max - y_min) s_x = [] s_y = [] s_l = [] for s in cycle: s_x_min = df.loc[df[h_cycle] == s, x].min() s_x_max = df.loc[df[h_cycle] == s, x].max() s_x_pos = (s_x_min + s_x_max) / 2 s_x.append(s_x_pos) s_y.append(s_y_pos) s_l.append(f"c{s}") c_labels = ColumnDataSource(data={x: s_x, y: s_y, "names": s_l}) c_labels = LabelSet( x=x, y=y, text="names", level="glyph", source=c_labels, render_mode="canvas", text_color="red", text_alpha=0.7, ) plot.add_layout(c_labels) # labelling steps if label_steps: for c in cycle: step = df.loc[df[h_cycle] == c, h_step].unique() step_line_positions = [ df.loc[(df[h_step] == s) & (df[h_cycle] == c), x].min() for s in step[0:] ] for m in step_line_positions: _s = Span( location=m, dimension="height", line_color="olive", line_width=3, line_alpha=0.1, ) plot.add_layout(_s) # s_y_pos = y_min + 0.8 * (y_max - y_min) s_x = [] s_y = [] s_l = [] for s in step: s_x_min = df.loc[(df[h_step] == s) & (df[h_cycle] == c), x].min() s_x_max = df.loc[(df[h_step] == s) & (df[h_cycle] == c), x].max() s_x_pos = s_x_min s_y_min = df.loc[(df[h_step] == s) & (df[h_cycle] == c), y].min() s_y_max = df.loc[(df[h_step] == s) & (df[h_cycle] == c), y].max() s_y_pos = (s_y_max + s_y_min) / 2 s_x.append(s_x_pos) s_y.append(s_y_pos) s_l.append(f"s{s}") s_labels = ColumnDataSource(data={x: s_x, y: s_y, "names": s_l}) s_labels = LabelSet( x=x, y=y, text="names", level="glyph", source=s_labels, render_mode="canvas", text_color="olive", text_alpha=0.3, ) plot.add_layout(s_labels) hover = HoverTool() if info_level == 0: hover.tooltips = [ (x, "$x{0.2f}"), (y, "$y"), ("cycle", f"@{h_cycle}"), ("step", f"@{h_step}"), ] elif info_level == 1: # insert C-rates etc here hover.tooltips = [ (f"(x,y)", "($x{0.2f} $y"), ("cycle", f"@{h_cycle}"), ("step", f"@{h_step}"), ("step_type", "@type"), ("rate", "@rate_avr{0.2f}"), ] elif info_level == 2: hover.tooltips = [ (x, "$x{0.2f}"), (y, "$y"), ("cycle", f"@{h_cycle}"), ("step", f"@{h_step}"), ("step_type", "@type"), ("rate (C)", "@rate_avr{0.2f}"), ("dv (%)", "@voltage_delta{0.2f}"), ("I-max (A)", "@current_max"), ("I-min (A)", "@current_min"), ("dCharge (%)", "@charge_delta{0.2f}"), ("dDischarge (%)", "@discharge_delta{0.2f}"), ] hover.mode = "vline" plot.add_tools(hover) plot.xaxis.axis_label = x_label plot.yaxis.axis_label = y_label if points: plot.scatter(x, y, source=source, alpha=0.3) if show_it: show(plot) return plot
x = [0, 1, 2, 3, 4, 5] y = [0, 1, 4, 9, 16, 25] # set output to static HTML file output_file("quad.html") # create a new plot with a title and axis labels p = figure(title="x^2 example", x_axis_label='x', y_axis_label='y', active_scroll="wheel_zoom") # add a line renderer with legend and line thickness p.line(x, y, legend_label="x-val legend label", line_width=2) # customize the hover_tool/tooltip hover_tool = HoverTool(tooltips=[("x val", "$x"), ("y val", "$y")]) hover_tool.point_policy = "snap_to_data" hover_tool.line_policy = "interp" # interpolate if between data points, makes it more continuous hover_tool.mode = "vline" #shows value if in line vertically (no need to be directly on top of graph line) p.add_tools(hover_tool) # remove tools on the right and logo for clean look p.toolbar.logo = None p.toolbar_location = None # show graph show(p)
fig.xaxis.axis_label = FIGURE_X_AXIS_LABEL fig.yaxis.axis_label = FIGURE_Y_AXIS_LABEL fig.xaxis.axis_label_standoff = FIGURE_X_AXIS_LABEL_STANDOFF fig.yaxis.axis_label_standoff = FIGURE_Y_AXIS_LABEL_STANDOFF fig.xaxis.axis_label_text_font_size = FIGURE_X_AXIS_FONT_SIZE fig.yaxis.axis_label_text_font_size = FIGURE_Y_AXIS_FONT_SIZE fig.xaxis.axis_label_text_font_style = FIGURE_X_AXIS_FONT_STYLE fig.yaxis.axis_label_text_font_style = FIGURE_Y_AXIS_FONT_STYLE fig.yaxis.minor_tick_line_color = None fig.xaxis.minor_tick_line_color = None fig.xaxis.ticker.mantissas = FIGURE_X_AXIS_MANTISSAS fig.xaxis.ticker.min_interval = FIGURE_X_AXIS_MIN_INTERVAL fig.xaxis.ticker.desired_num_ticks = FIGURE_X_AXIS_DESIRED_NUM_TICKS hover = HoverTool() hover.tooltips = HOVER_TOOLTIPS hover.mode = HOVER_MODE hover.renderers = [line] fig.add_tools(hover) ############################# Controls ############################## prevalence_control = Slider(title = PREVALENCE_TITLE, start = PREVALENCE_START, end = PREVALENCE_END, value = PREVALENCE_VALUE, step = PREVALENCE_STEP, format = NumeralTickFormatter(format = PREVALENCE_FORMAT), sizing_mode = PREVALENCE_SIZING_MODE) correlation_control = Slider(title = CORRELATION_TITLE, start = CORRELATION_START, end = CORRELATION_END, value = CORRELATION_VALUE,
def Hierarchical(doc): global source, nodes """" # df = pd.read_csv('application/dataSet/GephiMatrix_author_similarity.csv', sep=';') #csv_reader = pd.read_csv('application/dataSet/authors.csv', sep=';') ############################################################# # Make a condensed distance matrix ############################################################ # df_std = (df - df.min(axis=0)) / (df.max(axis=0) - df.min(axis=0)) # df_scaled = df_std * (1.0 - 0.0) + 0.0 # # dist = scipy.spatial.distance.squareform(distancematrix) # linkage_matrix = linkage(dist, "single") # results = dendrogram(linkage_matrix, no_plot=True) # icoord, dcoord = results['icoord'], results['dcoord'] # labels = list(map(int, results['ivl'])) # df = df.iloc[labels] # df_scaled = df_scaled.iloc[labels] # # tms = [] # # # icoord = pd.DataFrame(icoord) args = doc.session_context.request.arguments print(args) file = args.get('file')[0] file = str(file.decode('UTF-8')) with open("media/" + file) as data: csv_reader = csv.reader(data, delimiter=';') nArr = csv_reader.index.values dfArr = csv_reader.values nodes = dfArr names = nArr N = len(names) counts = np.zeros((N, N)) for i in range(0, len(nodes)): for j in range(0, len(nodes)): counts[i, j] = nodes[j][i] counts[j, i] = nodes[j][i] N = len(counts) distancematrix = np.zeros((N, N)) count = 0 for node_1 in counts: distancematrix[count] = node_1 count = count + 1 for m in range(N): for n in range(N): if distancematrix[m][n] == 0: distancematrix[m][n] = float("inf") for l in range(N): distancematrix[l][l] = 0 for k in range(N): for i in range(N): for j in range(N): if distancematrix[i][j] > distancematrix[i][k] + distancematrix[k][j]: distancematrix[i][j] = distancematrix[i][k] + distancematrix[k][j] values = distancematrix """ ######################################################################################################### def getLevelInfo(tree): nodes = [tree.get_left(), tree.get_right()] total_desc = tree.get_count() percents = [0] names = [] for node in nodes: percentage = float(node.get_count()) / float(total_desc) percents.append(float(percentage + percents[-1])) names.append(node.get_id()) return percents, names, nodes def genDataSource(tree): percents, names, nodes = getLevelInfo(tree) # define starts/ends for wedges from percentages of a circle starts = [p * 2 * pi for p in percents[:-1]] ends = [p * 2 * pi for p in percents[1:]] colours = getColours(len(starts)) branchLengths = [node.dist for node in nodes] children = [node.get_count() for node in nodes] source = ColumnDataSource(data=dict(start=starts, end=ends, name=names, colour=colours, branchLength=branchLengths, children=children)) return source, nodes def getColours(Length): colours = [ "red", "green", "blue", "orange", "yellow", "purple", "pink" ] returnColours = colours while len(returnColours) <= Length: returnColours += colours if returnColours[-1] == "red": returnColours[-1] = "orange" return returnColours[0:Length] def calcAngle(x, y): innerProduct = x lengthProduct = math.sqrt(x**2 + y**2) cosAngle = innerProduct / lengthProduct if y < 0 and x > 0: return 2 * pi - math.acos(cosAngle) else: return math.acos(cosAngle) def update(event): print('Click registered') angle = calcAngle(event.x, event.y) print(angle) global source, nodes for i in range(len(source.data['end'])): if source.data['end'][i] > angle and source.data['start'][ i] < angle: clickedNode = i print(i) if nodes[clickedNode].get_count() > 2: new_source, nodes = genDataSource(nodes[clickedNode]) source.data = new_source.data def returnVisualisation(): global source, nodes new_source, nodes = genDataSource(tree) source.data = new_source.data args = doc.session_context.request.arguments file = args.get('file')[0] file = str(file.decode('UTF-8')) try: df = pd.read_csv("media/" + file, sep=';') print('Loaded data succesfully') except: raise Exception("File does not exist") names = df.index.values counts = df.values # If data too large ######################################################### if len(names) > 50: n = 50 while len(names) != 50: names = np.delete(names, (n)) counts = np.delete(counts, (n), axis=0) counts = np.delete(counts, (n), axis=1) counts = np.delete(counts, len(counts), axis=1) # Make a distance matrix ####################################################### N = len(counts) distancematrix = np.zeros((N, N)) count = 0 for node_1 in counts: distancematrix[count] = node_1 count = count + 1 for m in range(N): for n in range(N): if distancematrix[m][n] == 0: distancematrix[m][n] = float("inf") for l in range(N): distancematrix[l][l] = 0 for k in range(N): for i in range(N): for j in range(N): if distancematrix[i][ j] > distancematrix[i][k] + distancematrix[k][j]: distancematrix[i][ j] = distancematrix[i][k] + distancematrix[k][j] X = distancematrix Z = linkage(X, 'ward') tree = to_tree(Z) ## Create the first data source for the root view source, nodes = genDataSource(tree) ## Create buttons and tools to interact with the visualisation returnButton = Button(label="Return") hover = HoverTool() hover.tooltips = [("Name", "@name"), ("Lenght to parent", "@branchLength"), ("Children", "@children")] hover.mode = 'mouse' tools = [hover, 'save'] ## Create the canvas p = figure(x_range=(-1, 1), y_range=(-1, 1), tools=tools) ## Draw the wedges on the canvas according to the tree info p.wedge(x=0, y=0, radius=1, start_angle='start', end_angle='end', color='colour', alpha=0.6, source=source) ## Map actions to events for the interaction p.on_event(events.Tap, update) returnButton.on_click(returnVisualisation) ## Display the visualisation doc.add_root(Column(returnButton, p))
def detail(request, id): """ Affiche la page détails site contenant 2 graphiques dont un composé de plusieurs module, ainsi qu'une description les boutons permettents d'interagir avec le graphique 1 Les graphiques possèdent quelques outils, tel que zoom, sauvegarde. **Context** ``graphique 1`` Contient le cours de la monnaie en cours ``graphique 2`` Contient le graphique avancé composé de plusieurs graphiques secondaire interactif ``description`` Une description ("definition.py") de la monnaie selectionné **Entrée** ``request`` la requete de l'utilisateur ``id`` String, nom de la monnaie **Sortie** ``script`` String du code js, pour le graphique 1 ``script2`` String du code js, pour le graphique 2 ``div`` objet graphique 1 afficher ``div2`` objet graphique 2 a afficher ``crypto`` String, nom de la monnaie ``about`` String, définition de la monnaie ``link`` String, lien wikipedia vers la monnaie ``template`` :template:`details.html` """ if (request.method == "POST"): #on vérifie si une méthode post exist if (request.POST.get("duree") ): #si dans le post existe alors on le récupère duree = request.POST.get('duree') if (request.POST.get("API")): bd = request.POST.get('API') if (request.COOKIES.get('pref_api') ): #s'il existe des préférences dans les cookies if 'duree' not in locals( ): #on vérifie si la variable existe (si elle existe c'est qu'on l'a instancié avec la méthode post) duree = request.COOKIES.get("pref_zoom") if 'bd' not in locals(): bd = request.COOKIES.get("pref_api") if 'duree' not in locals( ): #si même après ça les variables n'existent pas alors on leur donne une valeur par défaut duree = "um" if 'bd' not in locals(): bd = "binance" #=========================================== figure 1, graphique du prix de la monnaie res = get_main_data(bd, duree, id, "usd") #recupere les données necessaires pour le prix de la monnaie hover = HoverTool() hover.tooltips = [ ("prix", "@y{0,00}$"), ("date", "@x{%Y-%m-%d %H:%M:%S}"), ] hover.formatters = {'@x': 'datetime'} hover.mode = "vline" #on creer un hover, et on lui l'ensemble des champs titre (constant) et valeur (variable) des courbes en fonction de la position hover de la souris. #les valeurs afficher subissent des formatage pour plus de visiblite TOOLS = ['save', 'wheel_zoom', 'pan', 'box_zoom', 'reset'] #les outils du graphique df = pd.DataFrame(res) df['date'] = pd.to_datetime(df['date']) p = figure(plot_height=600, x_axis_type="datetime", tools=TOOLS, sizing_mode="stretch_width") #creation d'un objet figure p.tools.append(hover) #ajout du hover a la figure p.line(df['date'], df['usd'], color='navy', alpha=0.5) #on ajoute une courbe de type line a notre figure p.circle(df['date'], df['usd'], color='red', size=2) if duree == "j": txt_duree = " de la journée" elif duree == "s": txt_duree = " de la semaine" elif duree == "um": txt_duree = " du mois" elif duree == "sm": txt_duree = " des 6 derniers mois" elif duree == "a": txt_duree = " de l'année" else: txt_duree = "" p.title.text = "cours du " + id.title( ) + txt_duree + " avec " + bd.replace("_", " ").title() #mise en forme des titres p.xaxis.axis_label = 'temps' p.yaxis.axis_label = 'prix usd' p.background_fill_color = "white" p.xaxis.major_label_orientation = pi / 4 script, div = components(p) #genere un objet qui sera envoye au fichier html #=========================================== figure 2 graphique principal res2 = get_ind_data("CANDLE", id) #recuperation des donnees pour le graphe e chandelle df = pd.DataFrame(res2) df["date"] = pd.to_datetime(df["date"]) #pour generer un graphique chandelle, clandestick, on le decompose en plusieurs figures #des rectangles (vert ou rouge), et des segments (en arriere plan) permettant d avoir le min/max quotidiens mids = (df.Open + df.Close) / 2 spans = abs(df.Close - df.Open) inc = df.Close > df.Open dec = df.Open > df.Close w = 12 * 60 * 60 * 1000 #permet aussi de placer le rectangle dans le graphe #w permet d obtenir la largeur #inc et dec sont des panda series permettant de differencier les monte et les descende pour differencier les futur bonne couleur #mids nous sera utile pour avoir le milieu, necessaire pour la creation d un rectangle TOOLS = ['save', 'wheel_zoom', 'pan', 'box_zoom', 'reset'] #source drawn est un outils personnalise permettant de dessin a main leve #on l ajoute aux autre outils que nous proposons, permettant de se deplacer dans la figure, de faire des zoom ect p2 = figure(plot_height=600, x_axis_type="datetime", tools=TOOLS, sizing_mode="stretch_width") #creation de la deuxieme figure, qui contiendra l ensemble des courbes techniques cross = CrosshairTool() p2.add_tools(cross) #creation de crosshair, puis ajout a notre objet p2 p2.title.text = "Chandelier du " + id + " à intervalle journalier" p2.xaxis.major_label_orientation = pi / 4 p2.xaxis.axis_label = 'temps' p2.yaxis.axis_label = 'prix usd' p2.background_fill_color = "white" #initialisation des champs titres, et de propriete basique p2.segment(df.date, df.High, df.date, df.Low, color="black") #ajout de courbe segment, permettant de visualiser la valeur minimum et maximum quotidienne p2.rect(df.date[inc], mids[inc], w, spans[inc], fill_color="green", line_color="black") p2.rect(df.date[dec], mids[dec], w, spans[dec], fill_color="red", line_color="black") #ajout de courbe de type rectangle, permettant de visualiser la variation de l actif, entre la date d ouverture et fermeture de la journee #differenciation de couleur lorsqu on detecte une croissance en vert, ou une decroissance en rouge ################################### deuxième indicateur technique sur le graphique principal de la figure 2 data_bb = get_ind_data("BB", id) #recupere les données nécessaires pour indicateur Boilinger dfbb = pd.DataFrame(data_bb) band_source = ColumnDataSource(data=dict(date=df['date'], lowera=dfbb['Real Middle Band'], uppera=dfbb['Real Lower Band'], middlea=dfbb['Real Upper Band'])) c_hover = HoverTool() c_hover.tooltips = [ ('date', '@x{%F}'), ] c_hover.formatters = {'@x': 'datetime'} c_hover.name = 'lines1' maband = Band(base='date', lower='uppera', upper='middlea', fill_alpha=0.08, source=band_source, fill_color='blue') #creation de la courbe de type bande (glyph), les donnee necessaire a la creation sont passe par la bande_source, permettant de remplir #en transparant bleu, l'espace entre la courbe superieur et inferieur p2.line(df['date'], dfbb['Real Middle Band'], color='blue', alpha=1) #creation de courbe de type line, elle permet de mettre en evidence le milieu de la bande p2.add_layout(maband) #p2.add_tools(c_hover) ################################### troisième indicateur technique sur le graphique principal de la figure 2 data_pivot = get_ind_data("PP", id) #récupération des données pour les points de pivot dfp = pd.DataFrame(data_pivot) source_segment = ColumnDataSource( dict(x=df['date'], pp=dfp['PP'], s1=dfp['S1'], s2=dfp['S2'], s3=dfp['S3'], r1=dfp['R1'], r2=dfp['R2'], r3=dfp['R3'])) #on creer une source associe a nos rectangle, permettant de faire passer tout nos donnee necesaire. #on recupere la meme donnee date, du clandestick, elle est commune a toutes les courbes qui sont dans la p2 ainsi qu au graphique annexe. #en effet elle correspond au 100 dernier jour, a frequence de 1 points par jour p2.rect(x='x', y='r3', width=2 * w, height=0.0001, source=source_segment, fill_color="red", line_color="red", legend_label="r3") p2.rect(x='x', y='r2', width=2 * w, height=0.0001, source=source_segment, fill_color="red", line_color="red", legend_label="r2") p2.rect(x='x', y='r1', width=2 * w, height=0.0001, source=source_segment, fill_color="red", line_color="red", legend_label="r1") p2.rect(x='x', y='pp', width=2 * w, height=0.0001, source=source_segment, fill_color="black", line_color="black", legend_label="p") p2.rect(x='x', y='s1', width=2 * w, height=0.0001, source=source_segment, fill_color="green", line_color="green", legend_label="s1") p2.rect(x='x', y='s2', width=2 * w, height=0.0001, source=source_segment, fill_color="green", line_color="green", legend_label="s2") p2.rect(x='x', y='s3', width=2 * w, height=0.0001, source=source_segment, fill_color="green", line_color="green", legend_label="s3") #creation de 7 pivot de type rectangle, le rectangle est centré a la date x, puis deborde horizontalement de la date de "w" a gauche et a droite #la hauteur de 1, permet de simuler un trait. #le choix du rectangle (et non de Ray ou de Segment) a ete fait, car la courbe Rectangle permet de centré la figure, et que plus haut, nous avons #deja calculer la taille w #les pivots sont affiché par couleur differentes p2.legend.location = "top_right" p2.legend.click_policy = "hide" #permet d afficher une legende a gauche, avec nos 7 pivot #lorsqu un utilisateur clic sur la "legend_label" de la legend, il peut "hide" la courbe, permettant une visualisation plus personnalisé et propre ########################################################### figure 2 graphique annexe #ici on s occupe des graphiques annexe de la figure2 res2b = get_ind_data("MACD", id) #récupération des données pour le macd #le macd_hist = macd-macd_signal dfb = pd.DataFrame(res2b) p2b = figure(plot_height=300, x_axis_type="datetime", tools=TOOLS, sizing_mode="stretch_width", x_range=p2.x_range, background_fill_color="white") p2b.add_tools(cross) #création d une figure annexe avec qui est liée avec la principale #ils possedent la meme dimension de largeur, mais aussi le meme cross permettant de liée ses 2 graphiques macolor = [] for ele in dfb['MACD_Hist']: if ele is not None: if float(ele) < 0: macolor.append('red') else: macolor.append('green') else: macolor.append('green') #on possede les valeurs pour le digramme histogramme (a barre), maintenant on la parcours pour verifier les valeurs #et les noter dans un tableau p2b.vbar(x=df['date'], top=dfb['MACD_Hist'], color=macolor, width=w, alpha=0.5) #creation du digramme a barre, avec notre code couleur predefinis plus haut, ameliore la visibilite du client p2b.line(df['date'], dfb['MACD'], line_width=2, color='red', legend_label="macd") p2b.line(df['date'], dfb['MACD_Signal'], line_width=2, color='green', legend_label="macd_Signal") #affichage des courbes de type line p2b.legend.click_policy = "hide" p2b.legend.location = "top_right" tab1 = Panel(child=p2b, title="macd") #on cree un systeme d onglet dans notre graphique secondaire #puis on ajoute ce graphique secondaire ########################################################### figure 3 graphique annexe OBV client = InfluxDBClient(host=localhost, port=8086, database="alpha_vantage") #connexion a la bdd alpha_vantage res = client.query("select first(OBV) from " + id + " group by time(1d) order by time desc limit " + jour) #recuperation des donnees necessaire pour OBV (on balance volume) data_dic = {"obv": []} data_list = list(res)[0] for dic in data_list: if (dic.get("first")) != None: data_dic.get("obv").append(float(dic.get("first"))) else: data_dic.get("obv").append(dic.get("first")) data_dic.get('obv').reverse() dfObv = pd.DataFrame(data_dic) #netoyage des donnee permettant une plus simple manipluation p2obv = figure(plot_height=300, x_axis_type="datetime", tools=TOOLS, sizing_mode="stretch_width", x_range=p2.x_range, background_fill_color="white") p2obv.add_tools(cross) #creation d'une figure p2obv, qui partage le meme crosshair et x_range que la figure p2, permettant d avoir des graphiques liee hover_obv = HoverTool() hover_obv.tooltips = [ ("obv", "@y{0,00}"), ("date", "@x{%F}"), ] hover_obv.formatters = {'@x': 'datetime'} hover_obv.mode = "vline" p2obv.tools.append(hover_obv) #creation du hover, puis ajout sur la figure p2obv.line(df['date'], dfObv['obv'], line_width=1, color='blue', legend_label="obv") #creation de courne de type line p2obv.legend.location = "top_right" tab2 = Panel(child=p2obv, title="obv") #ajout de la figure sur un deuxieme onglet ########################################################### figure 3 graphique annexe RSI res = client.query("select first(RSI) from " + id + " group by time(1d) order by time desc limit " + jour) #recuperation des donnees necessaire pour OBV (on balance volume) data_dic = {"rsi": []} data_list = list(res)[0] for dic in data_list: if (dic.get("first")) != None: data_dic.get("rsi").append(float(dic.get("first"))) else: data_dic.get("rsi").append(dic.get("first")) data_dic.get('rsi').reverse() #netoyage des donnee permettant une plus simple manipluation dfRsi = pd.DataFrame(data_dic) p2rsi = figure(plot_height=300, x_axis_type="datetime", tools=TOOLS, sizing_mode="stretch_width", x_range=p2.x_range, background_fill_color="white") p2rsi.add_tools(cross) #creation d une figure, avec liaison avec la figure principe p2 #meme x_range, meme tools, permettant une syncrhonisation du zoom, des deplacements ect hover_rsi = HoverTool() hover_rsi.tooltips = [ ("rsi", "@y{0,00}"), ("date", "@x{%F}"), ] hover_rsi.formatters = {'@x': 'datetime'} hover_rsi.mode = "vline" p2rsi.tools.append(hover_rsi) p2rsi.line(df['date'], dfRsi['rsi'], line_width=1, color='blue', legend_label="rsi") #ajout de courbe de type line bandcst = Band(base='date', lower=30, upper=70, fill_alpha=0.08, source=band_source, fill_color='blue') p2rsi.add_layout(bandcst) #ajout d une bande, entre 30 et 70, car ce sont des valeurs remarquable utilise dans l analyse du rsi #il est donc pertinent d ajouter cet indicateur p2rsi.legend.location = "top_right" tab3 = Panel(child=p2rsi, title="rsi") tabs = Tabs(tabs=[tab1, tab2, tab3]) #ajout de la derniere figure en tant qu'onglet script2, div2 = components(column(p2, tabs)) #rendu en colonne, de la figure p2 et des graphiques secondaire represente en forme d onglet return render( request, 'accueil/detail.html', { 'script': script, 'script2': script2, 'div': div, 'div2': div2, 'crypto': id, 'about': definition.definition[id], 'link': definition.lien[id], })