def __init__(self, readers, rule): [self.reader] = readers self.rule = rule aligned = self.aligned() self.source = bom.ColumnDataSource(aligned) f = bop.figure(x_range=bom.DataRange1d(start=0, follow='end', range_padding=0), y_range=bom.DataRange1d(start=0), tooltips=[('', '$data_y')]) p = registry.parse_prefix(self.reader.prefix) n_bands = aligned.shape[1] - 1 assert n_bands % 2 == 1 for i in range(n_bands): color = Viridis256[255 - 256 * i // n_bands] lower = aligned.columns[i + 1] f.line(x='_time', y=f'{lower}', color=color, source=self.source) default_tools(f) styling(f) p = registry.parse_prefix(readers[0].prefix) f.title = bom.Title(text=p.group) self.figure = f
def _update_source(self, attr, old, new): # pylint: disable=unused-argument """Function to update the data `source` when new file inputs are given.""" decoded = base64.b64decode(new) f = io.BytesIO(decoded) df = inputs.read_midata(f) self.source.data = df self.all_plot.x_range = models.DataRange1d(bounds=(min(df.date), max(df.date))) max_amount = ( math.ceil(np.max(df[["balance", "abs_amount"]].values) / 1000) * 1000) self.all_plot.y_range = models.DataRange1d(bounds=(0, max_amount))
def initialize(): for scenario_name in scenarios: #build plots plot = { 'figure': bp.Figure(toolbar_location='right', tools='save,pan,box_zoom,reset', width=250, height=225), 'series': [], 'xmin': 0, 'xmax': 0, 'ymin': 0, 'ymax': 0, } plot['figure'].title.text = scenario_name plot['figure'].xaxis.major_label_orientation = 'vertical' plot['figure'].xaxis.major_label_standoff = 25 plot_list['scenarios'][scenario_name] = plot #build maps map_plot = bm.Plot(x_range=bm.DataRange1d(), y_range=bm.DataRange1d(), plot_width=450, plot_height=250, toolbar_location=None) map_plot.title.text = scenario_name map_list[scenario_name]['plot'] = map_plot combined_plot = { 'figure': bp.Figure(toolbar_location='right', tools='save,pan,box_zoom,reset', width=250, height=225), 'series': [], } combined_plot['figure'].title.text = 'Combined' combined_plot['figure'].xaxis.major_label_orientation = 'vertical' combined_plot['figure'].xaxis.major_label_standoff = 25 plot_list['combined'] = combined_plot build_plots() if showMaps: build_maps()
def __init__(self, readers, rule): self.readers = readers self.rule = rule self.source = bom.ColumnDataSource(self.aligned()) f = bop.figure(x_range=bom.DataRange1d(start=0, follow='end'), tooltips=[('', '$data_y')]) for reader, color in zip(readers, cycle(Category10_10)): p = registry.parse_prefix(reader.prefix) label = dict(legend_label=p.label) if p.label else dict() f.varea(x='_time', y1=f'{reader.prefix}.μ-', y2=f'{reader.prefix}.μ+', color=color, alpha=.2, source=self.source, **label) f.line(x='_time', y=f'{reader.prefix}.μ', color=color, source=self.source, **label) default_tools(f) x_zeroline(f) styling(f) p = registry.parse_prefix(readers[0].prefix) if p.label: legend(f) f.title = bom.Title(text=p.group) self.figure = f
def _timeseries(source, x, y): #TODO: Work out how to apply the axes formatters to the tooltips f = bop.figure(x_range=bom.DataRange1d(start=0, follow='end'), tooltips=[('', '$data_y')]) f.line(x=x, y=y, source=source) default_tools(f) x_zeroline(f) styling(f) return f
def _timedataframe(source, x, ys): f = bop.figure(x_range=bom.DataRange1d(start=0, follow='end'), tooltips=[('', '$data_y')]) for y, color in zip(ys, cycle(Category10_10)): f.line(x=x, y=y, legend_label=y, color=color, width=2, source=source) default_tools(f) x_zeroline(f) styling(f) f.legend.label_text_font_size = '8pt' f.legend.margin = 7 f.legend.padding = 0 f.legend.spacing = 0 f.legend.background_fill_alpha = 0.3 f.legend.border_line_alpha = 0. f.legend.location = 'top_left' return f
def make_multi_plot(merge): #s1 = figure(plot_width=400, plot_height=400, title=None) #s2 = figure(plot_width=400, plot_height=400, title=None) #merge = pd.DataFrame.from_csv('merge.csv') condition_1 = ((merge['bs_exp_offset'] >= 0) & (merge['bs_exp_offset'] <= 1)) condition_2 = ((merge['bs_exp_rsquared'] >= 0.8) & (merge['bs_exp_rsquared'] <= 1)) condition_3 = ((merge['select_line_aic_bs'] == False) & (merge['select_line_r_bs'] == False)) bs = merge[condition_1 & condition_2 & condition_3] X_bs = np.arange(-0.1, 13, 0.5) source = bkm.ColumnDataSource( dict( xs=[X_bs for i in bs.index.values], ys=[ model_deg(X_bs, bs.loc[n]['bs_exp_N0'], bs.loc[n]['bs_exp_tau'], bs.loc[n]['bs_exp_offset']) for n in bs.index.values ], )) xdr = bkm.DataRange1d() ydr = bkm.DataRange1d() s1 = bkm.Plot(title=None, x_range=xdr, y_range=ydr, plot_width=500, plot_height=500, toolbar_location='below') glyph = MultiLine(xs="xs", ys="ys", line_color="gray", line_width=1, line_alpha=0.1) s1.add_glyph(source, glyph) yaxis = bkm.LinearAxis() xaxis = bkm.LinearAxis() s1.add_layout(xaxis, 'below') s1.add_layout(yaxis, 'left') condition_1 = ((merge['pc_exp_offset'] >= 0) & (merge['pc_exp_offset'] <= 1)) condition_2 = ((merge['pc_exp_rsquared'] >= 0.8) & (merge['pc_exp_rsquared'] <= 1)) condition_3 = ((merge['select_line_aic_pc'] == False) & (merge['select_line_r_pc'] == False)) pc = merge[condition_1 & condition_2 & condition_3] X_pc = np.arange(-0.1, 28, 0.5) source2 = bkm.ColumnDataSource( dict( xs=[X_pc for i in pc.index.values], ys=[ model_deg(X_pc, pc.loc[n]['pc_exp_N0'], pc.loc[n]['pc_exp_tau'], pc.loc[n]['pc_exp_offset']) for n in pc.index.values ], )) xdr = bkm.DataRange1d() ydr = bkm.DataRange1d() s2 = bkm.Plot(title=None, x_range=xdr, y_range=ydr, plot_width=500, plot_height=500, toolbar_location='below') glyph = MultiLine(xs="xs", ys="ys", line_color="gray", line_width=1, line_alpha=0.1) s2.add_glyph(source2, glyph) yaxis = bkm.LinearAxis() xaxis = bkm.LinearAxis() s2.add_layout(xaxis, 'below') s2.add_layout(yaxis, 'left') #s2.add_layout(xaxis, 'below') #s2.add_layout(yaxis, 'left') s1.add_layout(bkm.Grid(dimension=0, ticker=xaxis.ticker)) s1.add_layout(bkm.Grid(dimension=1, ticker=yaxis.ticker)) s2.add_layout(bkm.Grid(dimension=0, ticker=xaxis.ticker)) s2.add_layout(bkm.Grid(dimension=1, ticker=yaxis.ticker)) return s1, s2
from bokeh.layouts import row, widgetbox, layout from bokeh.models.widgets import Slider, Select import pandas as pd from data_access import * # import relevant data PLOT_WIDTH = 850 PLOT_HEIGHT = 400 map_options = models.GMapOptions(lat=32.307660, lng=-64.848481, map_type="terrain", zoom=15) race_map = models.GMapPlot(x_range=models.DataRange1d(), y_range=models.DataRange1d(), map_options=map_options, plot_width=PLOT_WIDTH, plot_height=PLOT_HEIGHT) race_map.api_key = "AIzaSyBTnh7EZA33ChReBm449xwYxno1kE4w3EE" # add widgets frequency_slider = Slider(title="Frequency", value=25, start=5, end=100, step=5) date_select = Select(title='Date', value='170527', options=AC_schedule.keys()) start_slider = Slider(title="Start", value=-30, start=-500, end=-10, step=10)
def do_graph_animation(graph_product, title, path, progress_bar): # The total graph info plt.output_file(path) hover = bkm.HoverTool(tooltips=[("Country", "@names"), ("Region", "@region")]) f = plt.figure(title=title, x_axis_label=XLABEL, y_axis_label=YLABEL, tools=[ hover, bkm.WheelZoomTool(), bkm.BoxZoomTool(), bkm.PanTool(), bkm.SaveTool(), bkm.ResetTool() ], width=900) legend_list = [] sources = [] data = {} country_data = {} lowest_year = float("inf") highest_year = -float("inf") # Real quick, determine the boundries for region in graph_product: for timestamp in graph_product[region]: if timestamp > highest_year: highest_year = timestamp if timestamp < lowest_year: lowest_year = timestamp # Construct the new plot for region in graph_product: if region not in country_data: country_data[region] = {} lowest_region_year = float("inf") for timestamp in graph_product[region]: x_list, y_list = graph_product[region][timestamp] # Create the dataset data = {"x": [], "y": [], "names": [], "region": []} if timestamp < lowest_region_year: lowest_region_year = timestamp for country in x_list: country_price = x_list[country] country_BMI = y_list[country] # Save the data data["x"].append(country_price) data["y"].append(country_BMI) data["names"].append(country) data["region"].append(region) # Append country_data country_data[region][timestamp] = data # Now create a nice source of the data if lowest_region_year == lowest_year: data = country_data[region][lowest_year] else: data = { "x": [0] * len(country_data[region][lowest_region_year]["x"]), "y": [0] * len(country_data[region][lowest_region_year]["x"]), "names": country_data[region][lowest_region_year]["names"], "region": country_data[region][lowest_region_year]["region"] } data_source = bokeh.models.ColumnDataSource(data=data) sources.append([data_source, region]) # Now plot it region_color = REGION_NAME_2_COLOR[region] elem = f.scatter("x", "y", source=data_source, color=region_color, muted_color=region_color, muted_alpha=0.1, size=10) # Add elem to the legends legend_list.append((region, [elem])) # Do dat progress bar progress_bar.update() first_time = False legend = bokeh.models.Legend(items=legend_list, location=(0, 0), click_policy="mute") f.x_range = bkm.DataRange1d(start=0, end=3.6) f.y_range = bkm.DataRange1d(start=19, end=32) # Make the slider callback = bokeh.models.CustomJS(args=dict(sources=sources, all_data=country_data), code=callback_code) slider = bokeh.models.Slider(start=lowest_year, end=highest_year, value=lowest_year, step=1, title="Year") slider.js_on_change('value', callback) f.add_layout(legend, 'right') layout = bokeh.layouts.column(bokeh.layouts.widgetbox(slider), f) plt.save(layout)
def plot_all(self) -> plotting.Figure: """Creates plot containing all transations and balance over time. The plot will contain a line showing the balance over time, with scatter points to show the absolute value of each transation. Returns ------- plotting.Figure Figure object with all midata transactions plotted. """ balance_hover = models.HoverTool( names=["balance"], toggleable=False, tooltips=[ ("Date", "@date{%d/%m/%Y}"), ("Balance (£)", "@balance{0,0.00}"), ], formatters={"@date": "datetime"}, ) amount_hover = models.HoverTool( names=["abs_amount"], toggleable=False, tooltips=[ ("Date", "@date{%d/%m/%Y}"), ("Transaction (£)", "@amount{+0,0.00}"), ("Balance (£)", "@balance{+0,0.00}"), ("Merchant / Description", "@description"), ], formatters={"@date": "datetime"}, ) p = plotting.figure( title="All transactions", x_axis_label="Date", y_axis_label="Amount (£)", sizing_mode="stretch_both", tools=[ "pan", "box_select", "xwheel_zoom", "reset", "save", balance_hover, amount_hover, ], ) p.xaxis[0].formatter = models.DatetimeTickFormatter() p.y_range = models.DataRange1d(bounds=(0, 10000)) epoch = dt.datetime.utcfromtimestamp(0) max_date = (dt.datetime.today() - epoch).total_seconds() min_date = max_date - (2 * 365 * 24 * 60 * 60) p.x_range = models.DataRange1d(bounds=(min_date * 1000, max_date * 1000)) p.line( x="date", y="balance", source=self.source, legend_label="Balance", name="balance", line_width=2, ) p.scatter( "date", "abs_amount", size=5, color="colour", name="abs_amount", source=self.source, legend_label="Absolute Transaction", fill_alpha=0.8, ) p.legend.click_policy = "hide" return p