def box_annotations (Upper_Threshold, Lower_Threshold, plotname): low_box = BoxAnnotation(top=Lower_Threshold, fill_alpha=0.1, fill_color= None) mid_box = BoxAnnotation(bottom=Lower_Threshold, top=Upper_Threshold, fill_alpha=0.1, fill_color='red') high_box = BoxAnnotation(bottom=Upper_Threshold, fill_alpha=0.1, fill_color= None) plotname.add_layout(low_box) plotname.add_layout(mid_box) plotname.add_layout(high_box)
def plot_rsi(stock): p = figure(x_axis_type="datetime", plot_width=WIDTH_PLOT, plot_height=200, title="RSI 15 days", tools=TOOLS, toolbar_location='above') p.line(x='date', y='rsi_15', line_width=2, color=BLUE, source=stock) low_box = BoxAnnotation(top=30, fill_alpha=0.1, fill_color=RED) p.add_layout(low_box) high_box = BoxAnnotation(bottom=70, fill_alpha=0.1, fill_color=GREEN) p.add_layout(high_box) # Horizontal line hline = Span(location=50, dimension='width', line_color='black', line_width=0.5) p.renderers.extend([hline]) p.y_range = Range1d(0, 100) p.yaxis.ticker = [30, 50, 70] p.yaxis.formatter = PrintfTickFormatter(format="%f%%") p.grid.grid_line_alpha = 0.3 return p
def draw_rsi(rsi, title, margins=25): """ Draws RSI returns plot_script, plot_div """ colors = itertools.cycle(palette) prsi = figure(x_axis_type="datetime", plot_width=800, plot_height=150, y_range=(0, 100), title=title) for l in list(rsi): prsi.line(rsi.index, rsi[l], legend=l, line_color=next(colors)) prsi.line(rsi.index, [50] * rsi.shape[0], line_color='grey', line_dash='dotted') prsi.add_layout( BoxAnnotation(top=margins, fill_alpha=0.1, fill_color='red', line_color='red')) prsi.add_layout( BoxAnnotation(bottom=100 - margins, fill_alpha=0.1, fill_color='red', line_color='red')) prsi.legend.location = "top_left" return components(prsi)
def get_interval_boxannotation(self, cu_id): info = self.get_interval_cu(cu_id) mem_ld_interval_tree = info['mem_ld'] mem_st_interval_tree = info['mem_st'] other_interval_tree = info['other'] annotation_box_list = [] for interval in mem_ld_interval_tree: start = interval.begin end = interval.end box = BoxAnnotation(left=start, right=end, fill_alpha=0.1, fill_color='red') annotation_box_list.append(box) for interval in mem_st_interval_tree: start = interval.begin end = interval.end box = BoxAnnotation(left=start, right=end, fill_alpha=0.1, fill_color='blue') annotation_box_list.append(box) for interval in other_interval_tree: start = interval.begin end = interval.end box = BoxAnnotation(left=start, right=end, fill_alpha=0.1, fill_color='green') annotation_box_list.append(box) return (annotation_box_list, info)
def get_avg_ping_plot_by_time(averages_data): plot = figure(title="Ping over time", plot_width=1600, plot_height=800, x_axis_type="datetime") plot.y_range = Range1d(30, 120) plot.xaxis.axis_label = "Time(per 10 mins)" plot.yaxis.axis_label = "Ping(ms)" plot.line(x=averages_data.test_date, y=averages_data.ping, legend='ping', line_color='blue', line_width=2) plot.circle(x=averages_data.test_date, y=averages_data.ping, fill_color="white", line_color="blue", size=6) low_box = BoxAnnotation(plot=plot, top=60, fill_alpha=0.1, fill_color='green') mid_box = BoxAnnotation(plot=plot, bottom=60, top=90, fill_alpha=0.1, fill_color='yellow') high_box = BoxAnnotation(plot=plot, bottom=90, fill_alpha=0.1, fill_color='red') plot.renderers.extend([low_box, mid_box, high_box]) return plot
def plot_flight_modes_background(p, flight_mode_changes, vtol_states=None): """ plot flight modes as filling background (with different colors) to bokeh plot p """ vtol_state_height = 60 added_box_annotation_args = {} if vtol_states is not None: added_box_annotation_args['bottom'] = vtol_state_height added_box_annotation_args['bottom_units'] = 'screen' for i in range(len(flight_mode_changes)-1): t_start, mode = flight_mode_changes[i] t_end, mode_next = flight_mode_changes[i + 1] if mode in flight_modes_table: mode_name, color = flight_modes_table[mode] p.add_layout(BoxAnnotation(left=int(t_start), right=int(t_end), fill_alpha=0.09, line_color=None, fill_color=color, **added_box_annotation_args)) if vtol_states is not None: for i in range(len(vtol_states)-1): t_start, mode = vtol_states[i] t_end, mode_next = vtol_states[i + 1] if mode in vtol_modes_table: mode_name, color = vtol_modes_table[mode] p.add_layout(BoxAnnotation(left=int(t_start), right=int(t_end), fill_alpha=0.09, line_color=None, fill_color=color, top=vtol_state_height, top_units='screen')) # use screen coords so that the label always stays. It's a bit # unfortunate that the x position includes the x-offset of the y-axis, # which depends on the axis labels (e.g. 4.000e+5 creates a large offset) label = Label(x=83, y=32, x_units='screen', y_units='screen', text='VTOL mode', text_font_size='10pt', level='glyph', background_fill_color='white', background_fill_alpha=0.8) p.add_layout(label)
def create_bk_lmp_plot_1(lmps, pDopt, pCopt): p = figure( title="Selected LMPs", plot_width=p_width, plot_height=p_height, toolbar_location=None, ) p.toolbar.active_drag = None p.toolbar.active_scroll = None p.toolbar.active_tap = None p.xaxis.axis_label = "Period" p.yaxis.axis_label = "LMP ($/MWh)" N = len(lmps) x_range = list(range(N + 1)) labelx = 'LMP' p.step(x_range, list(lmps) + [lmps[-1]], line_width=2, mode='after', legend_label=labelx) for ii in range(N): if pDopt[ii] > 1e-3: p.add_layout( BoxAnnotation(left=x_range[ii], right=x_range[ii + 1], fill_alpha=0.2, fill_color='green')) elif pCopt[ii] > 1e-3: p.add_layout( BoxAnnotation(left=x_range[ii], right=x_range[ii + 1], fill_alpha=0.2, fill_color='red')) return p
def plot_water_levels_multiple(stations, dt, ncol=3, height=250, width=300): """ Function that displays a grid of graphs of the water level over time for a given list of stations. Args: stations (list): List of the desired stations (type MonitoringStation) to graph. dt (int): Number of days. ncol (int, optional): Number of columns. height (int, optional): Height of each individual plot. width (int, optional): Width of each individual plot. Returns: Bokeh plot object. """ plots = [] for station in stations: dates, levels = fetch_measure_levels(station.measure_id, dt=timedelta(days=dt)) p = figure(title=station.name, x_axis_label="Date", y_axis_label="Water level (m)") p.line(dates, levels, line_width=2) low = Span(location=station.typical_range[0], dimension='width', line_color='gray', line_dash="4 4", line_width=2) p.add_layout(low) high = Span(location=station.typical_range[1], dimension='width', line_color='gray', line_dash="4 4", line_width=2) p.add_layout(high) low_box = BoxAnnotation(top=station.typical_range[0], fill_alpha=0.1, fill_color='red') mid_box = BoxAnnotation(bottom=station.typical_range[0], top=station.typical_range[1], fill_alpha=0.1, fill_color='green') high_box = BoxAnnotation(bottom=station.typical_range[1], fill_alpha=0.1, fill_color='red') p.add_layout(low_box) p.add_layout(mid_box) p.add_layout(high_box) p.xaxis.formatter = DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) p.xaxis.major_label_orientation = np.pi / 4 plots.append(p) output_file("grid.html") grid = gridplot(plots, ncols=ncol, plot_width=width, plot_height=height) return grid
def get_box_beat_vertical(bar, beat, beat_per_bar, fill_alpha, line_alpha): box = BoxAnnotation(left=bar + beat / beat_per_bar, right=bar + beat / beat_per_bar + beat / beat_per_bar, fill_color=None, fill_alpha=fill_alpha, line_alpha=line_alpha) box.level = "underlay" return box
def multiply_signals(random_signal, f1=4): t = np.linspace(0, 1, random_signal.size) y_range = (-2, 2) y_ticks = [-1, 0, 1] fig1 = figure(title="x1", plot_width=700, plot_height=200, toolbar_location=None, y_range=y_range) bokeh_hide_all(fig1) fig1.yaxis.visible = True fig1.yaxis.ticker = y_ticks fig2 = figure(title="x2", plot_width=700, plot_height=200, toolbar_location=None, y_range=y_range) bokeh_hide_all(fig2) fig2.yaxis.visible = True fig2.yaxis.ticker = y_ticks fig3 = figure(title="x3 = x1 * x2", plot_width=700, plot_height=200, toolbar_location=None, y_range=y_range) bokeh_hide_all(fig3) fig3.yaxis.visible = True fig3.yaxis.ticker = y_ticks detector_signal = np.sin(f1 * np.pi * 2 * t) combined = random_signal * detector_signal w1_source = ColumnDataSource({'x': t, 'y': random_signal}) w2_source = ColumnDataSource({'x': t, 'y': detector_signal}) w3_source = ColumnDataSource({'x': t, 'y': combined}) fig1.line(x='x', y='y', source=w1_source, line_color='blue', line_width=2) fig2.line(x='x', y='y', source=w2_source, line_color='red', line_width=2) fig3.line(x='x', y='y', source=w3_source, line_color='purple', line_width=2) fig3.add_layout( BoxAnnotation(top=3, bottom=0, fill_alpha=0.1, fill_color='green')) fig3.add_layout( BoxAnnotation(top=0, bottom=-3, fill_alpha=0.1, fill_color='red')) handle = show(column(fig1, fig2, fig3), notebook_handle=True) def update(f1=5): new_signal = np.sin(f1 * np.pi * 2 * t) w2_source.data.update({'y': new_signal}) w3_source.data.update({'y': random_signal * new_signal}) push_notebook(handle) return update
def _get_log_plots(log_data): time_stamp = log_data[0] height = log_data[1] yaw = _shift_yaw(log_data[2]) pitch = log_data[3] roll = log_data[4] is_video = log_data[5] height_plot = figure(title='Height', plot_width=700, plot_height=500) height_plot.xaxis.formatter = DatetimeTickFormatter(minsec=['%H:%M:%S'], minutes=['%H:%M:%S'], hourmin=['%H:%M:%S']) height_plot.yaxis.axis_label = 'Meters' height_plot.line(time_stamp, height) yaw_plot = figure(title='Yaw', plot_width=700, plot_height=500, x_range=height_plot.x_range) yaw_plot.xaxis.formatter = DatetimeTickFormatter(minsec=['%H:%M:%S'], minutes=['%H:%M:%S'], hourmin=['%H:%M:%S']) yaw_plot.yaxis.axis_label = 'Degrees' yaw_plot.line(time_stamp, yaw) pitch_plot = figure(title='Pitch', plot_width=700, plot_height=500, x_range=height_plot.x_range) pitch_plot.xaxis.formatter = DatetimeTickFormatter(minsec=['%H:%M:%S'], minutes=['%H:%M:%S'], hourmin=['%H:%M:%S']) pitch_plot.yaxis.axis_label = 'Degrees' pitch_plot.line(time_stamp, pitch) roll_plot = figure(title='Roll', plot_width=700, plot_height=500, x_range=height_plot.x_range) roll_plot.xaxis.formatter = DatetimeTickFormatter(minsec=['%H:%M:%S'], minutes=['%H:%M:%S'], hourmin=['%H:%M:%S']) roll_plot.yaxis.axis_label = 'Degrees' roll_plot.line(time_stamp, roll) for video_range in get_video_ranges(is_video, time_stamp): video_box1 = BoxAnnotation(left=video_range[0], right=video_range[1], fill_color='#cccccc') video_box2 = BoxAnnotation(left=video_range[0], right=video_range[1], fill_color='#cccccc') video_box3 = BoxAnnotation(left=video_range[0], right=video_range[1], fill_color='#cccccc') video_box4 = BoxAnnotation(left=video_range[0], right=video_range[1], fill_color='#cccccc') height_plot.add_layout(video_box1) yaw_plot.add_layout(video_box2) pitch_plot.add_layout(video_box3) roll_plot.add_layout(video_box4) return height_plot, yaw_plot, pitch_plot, roll_plot
def plot_water_level_with_fit(station, dates, levels, p): """ Function that makes a graph of the water level over time for a given station with a least-square fit polynomial with a degree of p. Args: station (MonitoringStation): The desired station to graph. dates (list): The list of dates for the x-axis. levels (list): The corresponding water level for each date, y-axis. p (int): The degree of polynomial that is desired. Returns: Bokeh plot object. """ output_file(station.name + ".html") graph = figure(title=station.name, x_axis_label="Date", y_axis_label="Water level (m)") graph.line(dates, levels, line_width=2) poly, d0 = polyfit(dates, levels, p) graph.line(dates, [poly(date - d0) for date in date2num(dates)], line_width=2, line_color='orange') low = Span(location=station.typical_range[0], dimension='width', line_color='gray', line_dash="4 4", line_width=2) graph.add_layout(low) high = Span(location=station.typical_range[1], dimension='width', line_color='gray', line_dash="4 4", line_width=2) graph.add_layout(high) low_box = BoxAnnotation(top=station.typical_range[0], fill_alpha=0.1, fill_color='gray') mid_box = BoxAnnotation(bottom=station.typical_range[0], top=station.typical_range[1], fill_alpha=0.1, fill_color='green') high_box = BoxAnnotation(bottom=station.typical_range[1], fill_alpha=0.1, fill_color='red') graph.add_layout(low_box) graph.add_layout(mid_box) graph.add_layout(high_box) graph.xaxis.formatter = DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) graph.xaxis.major_label_orientation = np.pi / 4 return graph
def altitude(self): self.fig.add_layout( BoxAnnotation(bottom=75, fill_alpha=0.1, fill_color='yellow', line_color='yellow')) self.fig.add_layout( BoxAnnotation(top=30, fill_alpha=0.1, fill_color='yellow', line_color='yellow'))
def get_ping_plot_by_host(data): data.drop([ 'id', 'net_type', 'packet_loss', 'ping_max', 'ping_min', 'upload', 'ping_loc', 'ip_address', 'ping', 'hosted_by', 'download' ], axis=1, inplace=True) plot = figure(title="Ping over time", plot_width=1600, plot_height=800, x_axis_type="datetime") plot.y_range = Range1d(0, 150) plot.xaxis.axis_label = "Time(per 10 mins)" plot.yaxis.axis_label = "Ping(ms)" dic = { x: data.ping_avg[data.hostname == x] for x in data.hostname.unique() } dix = { x: data.test_date[data.hostname == x] for x in data.hostname.unique() } i = 0 for host in data.hostname.unique().tolist(): plot.line(x=dix[host].values, y=dic[host].values, line_width=2, line_color=Spectral7[i], legend=host) plot.circle(x=dix[host].values, y=dic[host].values, fill_color="white", size=6) i += 1 low_box = BoxAnnotation(plot=plot, top=60, fill_alpha=0.1, fill_color='green') mid_box = BoxAnnotation(plot=plot, bottom=60, top=90, fill_alpha=0.1, fill_color='yellow') high_box = BoxAnnotation(plot=plot, bottom=90, fill_alpha=0.1, fill_color='red') plot.renderers.extend([low_box, mid_box, high_box]) return plot
def login(): hover2 = HoverTool(tooltips=[("Volatility", "$y")]) xyvalues = OrderedDict( Date=df1['Date'], FaceBook=df1['Close'], Apple=df4['Close'], MSFT=df3['Close'], IBM=df2['Close'], ) t = TimeSeries(xyvalues, width=800, height=800, index='Date', legend=True, title="Comparison of Stocks", ylabel='Prices') r = figure(width=800, height=400, x_axis_type="datetime", tools=[hover2]) r.line(df1['Date'], df1['Volitility'], color='red', legend="Facebook") r.line(df2['Date'], df2['Volitility'], color='blue', legend="IBM") r.line(df3['Date'], df3['Volitility'], color='brown', legend="MicroSoft") r.line(df4['Date'], df4['Volitility'], color='green', legend="Apple") r.legend.orientation = "top_left" low_box = BoxAnnotation(plot=r, top=-2, fill_alpha=0.1, fill_color='red') mid_box = BoxAnnotation(plot=r, bottom=-2, top=2, fill_alpha=0.1, fill_color='green') high_box = BoxAnnotation(plot=r, bottom=2, fill_alpha=0.1, fill_color='red') r.renderers.extend([low_box, mid_box, high_box]) r.title = "Volatility in last month" r.xgrid[0].grid_line_color = None r.ygrid[0].grid_line_alpha = 0.5 r.xaxis.axis_label = 'Date' r.yaxis.axis_label = 'Value' script3, div3 = components(t) script4, div4 = components(r) return render_template('compare.html', script3=script3, div3=div3, script4=script4, div4=div4)
def from_csv_path(cls, bokeh_document: Document, csv_path: Path) -> Viewer: """ Creates a viewer from a CSV path containing a light curve path column. :param bokeh_document: The Bokeh document to run the viewer in. :param csv_path: The path to the CSV file. :return: The viewer. """ viewer = cls() viewer.document = bokeh_document viewer.csv_path = csv_path viewer.light_curve_display = LightCurveDisplay.for_columns(TessFfiColumnName.TIME__BTJD.value, TessFfiLightCurve().flux_column_names, flux_axis_label='Relative flux') viewer.light_curve_display.exclude_outliers_from_zoom = True viewer.maximum_physical_depth_box = BoxAnnotation(bottom=1-0.01, top=1, fill_alpha=0.1, fill_color='green') viewer.light_curve_display.figure.add_layout(viewer.maximum_physical_depth_box) viewer.add_to_positives_button = viewer.create_add_to_positives_button() bokeh_document.add_root(viewer.add_to_positives_button) viewer.previous_button, viewer.next_button = viewer.create_light_curve_switching_buttons() bokeh_document.add_root(viewer.previous_button) bokeh_document.add_root(viewer.next_button) viewer.information_div = Div() viewer.information_div.sizing_mode = 'stretch_width' bokeh_document.add_root(viewer.information_div) bokeh_document.add_root(viewer.light_curve_display.figure) loop = asyncio.get_running_loop() loop.create_task(viewer.start_preloader(csv_path)) return viewer
def plot_cheapest_shops(self, df, n=10): df = df.reindex() y = np.asarray(df.groupby(['shop']).price.min().values, dtype=np.float32) x = df.index mid_prices, upper_range, lower_range = self.get_price_range(df) mapper = linear_cmap(field_name='y', palette=Spectral6, low=min(y), high=max(y)) p = figure(plot_width=500, plot_height=500, title="") color_bar = ColorBar(color_mapper=mapper['transform'], width=8, location=(0, 0)) mid_box = BoxAnnotation(bottom=lower_range, top=upper_range, fill_alpha=0.1, fill_color='green') p.add_layout(mid_box) p.y_range = Range1d(0, max(y)) p.add_layout(color_bar, 'right') p.scatter(x=x[:n], y=y[:n], line_color=mapper, color=mapper, fill_alpha=1, size=12) output_file("scatter.html") show(p)
def bscoreCumulative(self, figurename, dataname): """----------------------------------------------------------------------------------------- Bokeh plot of cumulative distribution as a line on right hand axis :param figurename: string, name of figures (stored in self.figure) :param dataname: string, name of data frame (stored in self.frame) :return: True -----------------------------------------------------------------------------------------""" data = self.frame[dataname] figure = self.figure[figurename] source = ColumnDataSource(data) figure.extra_y_ranges = {"cumulative": Range1d(start=0.0, end=1.0)} axis2 = LinearAxis(y_range_name="cumulative") axis2.ticker.num_minor_ticks = 10 figure.add_layout(axis2, 'right') figure.line(source=source, x='score', y='cumulative', y_range_name='cumulative', line_width=2, color='#1122cc') # shaded box showing 95% level box = BoxAnnotation(bottom=0.95, top=1.0, y_range_name='cumulative', fill_color='#FFBBBB', line_width=3, line_dash='dashed') figure.add_layout(box) return True
def make_plot(source, property_name, num_years): p = figure(toolbar_location=None, width=800, x_axis_type="datetime", x_axis_label='Date', y_axis_label='Predicted Daily Occupancy Rate') title = 'Predicted Daily Occupancy For:' p.line('day', 'occupied', color='red', alpha=0.4, # line_dash='dashed', legend='Historic Actual of Daily Average Occupancy Rate', source=source) p.circle('day', 'prob_1', size=3, color='blue', alpha=0.7, # color='blue', legend='Prediction of Future Daily Occupancy', source=source) p.title.text = title p.title.text_font_size = '34pt' p.legend.location = "top_left" p.ygrid.band_fill_alpha = 0.2 p.grid.grid_line_alpha = .3 p.axis.axis_label_text_font_style = "bold" p.x_range = DataRange1d(range_padding=0.0) p.add_layout(BoxAnnotation(bottom=.6, fill_alpha=0.1, fill_color='blue')) p.themed_values() return p
def get_graph(data): data['Judge Name'] = data['Last'] + ', ' + data['First'] data['Judge Name'] = data['Judge Name'].astype(str) data = data.drop_duplicates(subset=['Judge Name']) judge_names = data['Judge Name'].values tooltips = [('', '@{Recess Hover}'), ('', '@{Nominate Hover}'), ('', '@{Confirm Hover}'), ('', '@{Oath Hover}')] source = ColumnDataSource(data) fig =figure(y_range = judge_names, height = 1600, width = 1200, tooltips=tooltips) fig.hbar(left = 'Recess', right = 'Gap Last Day to Nominate', y='Judge Name', source=source, color='#00BFB2', height=0.8, legend='Recess Appointment to Official Submission of Nomination to Senate') fig.hbar(left = 'Gap Last Day to Nominate', right = 'Gap Last Day to Confirm Vote', y='Judge Name', source=source, color='#028090', height=0.8, legend='Nomination to Confirmation') fig.hbar(left='Gap Last Day to Confirm Vote', right = 'Gap Last Day to Oath Date', y='Judge Name', source=source, color='#C64191', height=0.8, legend='Confirmation to Oath') fig.circle(x = 'First Judge Nom', y='Judge Name', source=source, color='black', radius=5, legend='Previous Non-Confirmed Nomination') fig.circle(x='Second Judge Nom', y='Judge Name', source=source, color='black', radius=5, legend='Previous Non-Confirmed Nomination') fig.circle(x='Third', y='Judge Name', source=source, color='black', radius=5, legend='Previous Non-Confirmed Nomination') fig.circle(x='Fourth', y='Judge Name', source=source, color='black', radius=5, legend='Previous Non-Confirmed Nomination') fig.circle(x='Fifth', y='Judge Name', source=source, color='black', radius=5, legend='Previous Non-Confirmed Nomination') fig.xaxis.axis_label = 'Days After (or Before) Predecessor''s Final Day on Court' fig.legend.title = 'Number of Days between Predecessor''s Last Day and:' fig.add_layout(fig.legend[0], 'right') ticks = [0, 46, 104, 123, 365, 730] fig.xaxis[0].ticker = ticks fig.xgrid[0].ticker = ticks mid_box = BoxAnnotation(left=46, right=123, fill_alpha=0.1, fill_color='green') fig.add_layout(mid_box) gb_citation = Label(x=400, y=1300, x_units='screen', y_units='screen', text='Green box starts on election day 2020 (43 days after death of RBG) and ends on inauguration day 2021 (123 days). (104 days until new senate is sworn in)', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) bl_citation = Label(x=400, y=1350, x_units='screen', y_units='screen', text='Black dashed line represents the last day served by the previous justice', render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) fig.add_layout(gb_citation) fig.add_layout(bl_citation) fig.xaxis.major_label_orientation = "vertical" xhighlight = Span(location=0, dimension='height', line_color='black', line_dash='dashed', line_width=3) fig.add_layout(xhighlight) fig.toolbar.logo = None fig.toolbar_location = None return fig
def test_BoxAnnotation() -> None: box = BoxAnnotation() assert box.left is None assert box.left_units == 'data' assert box.right is None assert box.right_units == 'data' assert box.bottom is None assert box.bottom_units == 'data' assert box.top is None assert box.top_units == 'data' assert box.x_range_name == 'default' assert box.y_range_name == 'default' assert box.level == 'annotation' check_line_properties(box, "", '#cccccc', 1, 0.3) check_fill_properties(box, "", "#fff9ba", 0.4) check_properties_existence(box, [ "render_mode", "visible", "left", "left_units", "right", "right_units", "bottom", "bottom_units", "top", "top_units", "x_range_name", "y_range_name", "level", ], LINE, FILL)
def getTimeSeries_old(df_tws): df_tws['date'] = pd.to_datetime(df_tws['date'], format='%m/%d/%Y') print(df_tws) #grouped = df_tws.groupby('date')['sentiment'].sum() grouped = df_tws.groupby(pd.Grouper(key='date', freq='D'))['sentiment', 'sentiment'].count() source = ColumnDataSource(grouped) p = figure(plot_height=400, x_axis_type='datetime') p.line(x='date', y='sentiment', line_width=2, source=source, legend='sentiment') p.line(x='date', y='sentiment', line_width=2, source=source, legend='sentiment') p.yaxis.axis_label = 'Number of Tweets' box_left = pd.to_datetime('25-2-2020') box_right = pd.to_datetime('5-3-2020') box = BoxAnnotation(left=box_left, right=box_right, line_width=1, line_color='black', line_dash='dashed', fill_alpha=0.2, fill_color='orange') p.add_layout(box) return p
def test_BoxAnnotation() -> None: box = BoxAnnotation() assert box.left is None assert box.left_units == "data" assert box.right is None assert box.right_units == "data" assert box.bottom is None assert box.bottom_units == "data" assert box.top is None assert box.top_units == "data" assert box.x_range_name == "default" assert box.y_range_name == "default" assert box.level == "annotation" check_line_properties(box, "", "#cccccc", 1, 0.3) check_fill_properties(box, "", "#fff9ba", 0.4) check_hatch_properties(box) check_properties_existence( box, ANNOTATION + [ "left", "left_units", "right", "right_units", "bottom", "bottom_units", "top", "top_units", ], LINE, FILL, HATCH)
def plot_steps(out_dict, units): """ Plot convergence steps in Bokeh """ from bokeh.models import BoxAnnotation from bokeh.plotting import figure, show, output_notebook import bokeh.models as bmd tooltips = [("Step (total)", "@index"), ("Step (stage)", "@step"), ("Energy", "@energy eV/atom"), ("Energy (dispersion)", "@dispersion_energy_au Ha"), ("SCF converged", "@scf_converged"), ("Cell A", "@cell_a_angs Angs"), ("Cell Vol", "@cell_vol_angs3 Angs^3"), ("MAX Step", "@max_step_au Bohr"), ("Pressure", "@pressure_bar bar")] hover = bmd.HoverTool(tooltips=tooltips) TOOLS = ["pan", "wheel_zoom", "box_zoom", "reset", "save", hover] natoms = out_dict['natoms'] values = [ x / natoms * ha2u[units] for x in out_dict['step_info']['energy_au'] ] values = [x - min(values) for x in values] data = bmd.ColumnDataSource(data=dict( index=range(len(values)), step=out_dict['step_info']['step'], energy=values, dispersion_energy_au=out_dict['step_info']['dispersion_energy_au'], scf_converged=out_dict['step_info']['scf_converged'], cell_a_angs=out_dict['step_info']['cell_a_angs'], cell_vol_angs3=out_dict['step_info']['cell_vol_angs3'], max_step_au=out_dict['step_info']['max_step_au'], pressure_bar=out_dict['step_info']['pressure_bar'], )) p = figure(tools=TOOLS, title='Energy profile of the DFT minimization', height=350, width=550) p.xgrid.grid_line_color = None p.xaxis.axis_label = 'Steps' p.yaxis.axis_label = 'Energy ({}/atom)'.format(units) # Colored background colors = ['red', 'orange', 'green', 'yellow', 'cyan', 'pink', 'palegreen'] start = 0 for i, steps in enumerate(out_dict['stage_info']['nsteps']): end = start + steps p.add_layout( BoxAnnotation(left=start, right=end, fill_alpha=0.2, fill_color=colors[i])) start = end # Trace line and markers p.line('index', 'energy', source=data, line_color='blue') p.circle('index', 'energy', source=data, line_color='blue', size=3) return p
def _init_glyph(self, plot, mapping, properties): """ Returns a Bokeh glyph object. """ box = BoxAnnotation(level=properties.get('level', 'glyph'), **mapping) plot.renderers.append(box) return None, box
def makeGraph(self): TOOLS = "pan,wheel_zoom,box_zoom,reset,save" x = [] y = [] # bit messy - need to fix indexing on x f = open("graphingtest.csv") for line in f: print((line.strip('\n').split(',')[0][-6:])) x.append(float(line.strip('\n').split(',')[0][-6:])) y.append(line.strip('\n').split(',')[1]) r = x[0] x = [n - r for n in x] print(x) print(y) p = figure(x_axis_type="linear", tools=TOOLS, title="Threshold") p.background_fill_color = "#efefef" p.xgrid.grid_line_color = None p.xaxis.axis_label = 'Time' p.yaxis.axis_label = 'Value' p.line(x, y, line_color='grey') # for fix after figuring out math # fix the subtraction factor to be relative green_number = float(max(y)) - 1.5 red_number = float(max(y)) - 0.5 p.add_layout( BoxAnnotation(bottom=red_number, fill_alpha=0.2, fill_color='red')) p.add_layout( BoxAnnotation(top=green_number, fill_alpha=0.2, fill_color='green')) p.add_layout( BoxAnnotation(bottom=green_number, top=red_number, fill_alpha=0.2, fill_color='yellow')) output_file("threshold.html", title=self.file_name) export_png(p, filename="graph.png")
def generate_harmonic_plot(harmonic_col, energy_source_list, y_range=(0, 25), L=5, size=750): plot = figure(y_range=y_range, plot_width=size, plot_height=size, title='Energy levels of harmonic oscillator') plot.yaxis.axis_label = 'E' plot.yaxis.axis_label_text_font_size = '24pt' plot.xaxis.axis_label = 'r - r0' plot.xaxis.axis_label_text_font_size = '24pt' plot.line('x', 'y', source=harmonic_col, line_width=6, color='blue', line_alpha=1, legend='Harmonic oscillator potential') for i in range(1, len(energy_source_list)): if i == 1: plot.line('x', 'y', source=energy_source_list[i], line_width=3, line_alpha=0.8, color='red', legend='Zero point energy (E(n=1))') if i in range(2, 5): plot.line('x', 'y', source=energy_source_list[i], line_width=3, line_alpha=0.8, color='red', legend='E(n=%s)' % i) else: plot.line('x', 'y', source=energy_source_list[i], line_width=3, line_alpha=0.8, color='red') positive_marker = BoxAnnotation(bottom=0, top=100, fill_color='blue', fill_alpha=0.05) plot.add_layout(positive_marker) plot.legend.location = 'top_left' plot.legend.click_policy = 'hide' return plot
def plotter(x_axis, y_axis, y_error, p, legend_label='', y_label_name='Magnification', color='purple', plot_errorbar=False, t0_error_plot=False, t0=None, t0_error=None): """ Produce plot for the event :return: None """ p.xaxis.axis_label = 'Days' p.yaxis.axis_label = y_label_name p.circle(x_axis, y_axis, fill_alpha=0.2, size=5, legend_label=legend_label, color=color) if plot_errorbar: upper = [x + e for x, e in zip(y_axis, y_error)] lower = [x - e for x, e in zip(y_axis, y_error)] source = ColumnDataSource( data=dict(groups=x_axis, counts=y_axis, upper=upper, lower=lower)) p.add_layout( Whisker(source=source, base="groups", upper="upper", lower="lower", level="overlay")) if t0_error_plot: t0_location = Span(location=t0, dimension='height', line_color='red', line_dash='dashed', line_width=1) p.add_layout(t0_location) box = BoxAnnotation(left=(t0 - t0_error), right=(t0 + t0_error), line_width=1, line_color='black', line_dash='dashed', fill_alpha=0.2, fill_color='orange') p.add_layout(box) return p
def scatterplot(df, daysinchart): from bokeh.plotting import figure from bokeh.io import output_file, show, save from bokeh.models import BoxAnnotation x = df["Date"].tail(daysinchart) y = df["Endring pris"].tail(daysinchart) * 100 Selskapsnavn = str(df["INSTRUMENT"].iloc[-1]) StdAvvik = round(df["Endring pris"].std() * 100, 2) TOOLS = "pan,wheel_zoom,zoom_in,zoom_out,box_zoom,reset,tap,save,box_select,poly_select,lasso_select," p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, title=str(Selskapsnavn) + " - Daily Ccanges - Standard deviation: " + str(StdAvvik) + " percent") p.toolbar.logo = None # Fjerner Bokeh logoen fra chartet p.image_url(url=[bilde_Logo], x=x.max() - ((x.max() - x.min()) / 2), y=y.max() - ((y.max() - y.min()) / 2), w=x.max() - x.min(), h=y.max() - y.min(), anchor='center', alpha=0.2) # legger til logo low_box = BoxAnnotation(top=0, fill_alpha=0.1, fill_color='red') high_box = BoxAnnotation(bottom=0, fill_alpha=0.1, fill_color='green') p.add_layout(low_box) p.add_layout(high_box) p.scatter(x, y, fill_color="black", fill_alpha=0.8, line_color=None, size=8) output_file("candlestick.html", title="color_scatter.py example") show(p)
def addline(self, fig): "add a vertical line at the current zmag" zmag = self.__theme.value self.__box = BoxAnnotation(left=zmag, right=zmag, fill_alpha=0., line_alpha=self.__theme.alpha, line_color=self.__theme.color) fig.add_layout(self.__box)