def tick_formater(self, data_type): if data_type == 'datetime': formatter = DatetimeTickFormatter(**dict(days='%Y-%m-%d', months='%Y-%m', hours='%Y-%m-%d %H', minutes='%Y-%m-%d %H:%M')) elif data_type == 'integer': print('integer') formatter = NumeralTickFormatter(format='0,0') elif data_type == 'float': print('float') formatter = NumeralTickFormatter(format='0.000') return formatter
def make_plot_cntry(data: DF, scale: str = "linear", country="Colombia", x_tools: List[str] = None): """Make a bokeh plot of a certain type (confirmed/recovered/deaths/active) scale can be "linear" or "log" for a bunch of countries""" klasses = ["active", "deaths", "recovered", "confirmed"] p = init_plot( scale, x_tools=x_tools ) data_source = data_source_ctry(data, country=country) all_colors = Category10[10] klass_2_color = { 'active': all_colors[1], 'recovered': all_colors[2], 'deaths': all_colors[3], 'confirmed': all_colors[0], } for klass in klasses: color = klass_2_color[klass] # visible = country in (ACTIVE_COUNTRIES.union(x_countries)) draw_country_line(p, source=data_source, country=country, klass=klass, legend=TRANSL.get(klass, klass), color=color, visible=True ) # set_hover_tool(p, klass) set_hover_tool_ctry( p ) p.legend.location = "top_left" p.legend.click_policy = "hide" p.yaxis.formatter = NumeralTickFormatter(format='0,0') p.xaxis.formatter = DatetimeTickFormatter(days=["%b %d"]) # output_file(OUTPUT_DIR / f"{klass}.html", title=f"Cases by country - {klass}") return p
def make_cmp_plot(data: DF, klass: str, scale: str = "linear", x_tools: List[str] = None, countries: List[str] = None, x_countries: List[str] = None ): """Make a bokeh plot of a certain type (confirmed/recovered/deaths/active) scale can be "linear" or "log" for a bunch of countries""" x_countries = x_countries or [] countries = countries or COUNTRIES print( 'c1', countries ) if scale == 'log' and 'World' not in countries: countries = ['World'] + countries print('c2', countries) countries = x_countries + [ c for c in countries if c not in x_countries ] countries = countries[:10] p = init_plot( scale, x_tools ) for country, color in zip(countries, Category10[10]): data_src = data_source_ctry( data, country ) visible = country in (ACTIVE_COUNTRIES.union(x_countries)) legend = TRANSL.get( country, country ) draw_country_line(p, data_src, country, klass, color, visible, legend ) set_hover_tool(p, klass) p.legend.location = "top_left" p.legend.click_policy = "hide" p.yaxis.formatter = NumeralTickFormatter(format='0,0') p.xaxis.formatter = DatetimeTickFormatter(days=["%b %d"]) # output_file(OUTPUT_DIR / f"{klass}.html", title=f"Cases by country - {klass}") return p
def create_figure(): ''' The main function to aggregate the data and create the figure. ''' use_df = select_data() # Get the filtered dataframe agg = pivot_data(use_df) # aggregate the dataframe source = ColumnDataSource(agg) # put into a bokeh data structure hover = HoverTool( # Set the hover tools, ('Title', '@Column{formatting}'') tooltips = [ ('Year', '@Year'), ('Total Murders','@MRD{0,0}'), ('Solved Murders','@Yes{0,0}'), ('Clearance Rate','@Clearance_Rate{0%}') ] ) tools=[hover, ResetTool()] p = figure(plot_width=900, plot_height=550,tools=tools) # Create figure p.xaxis.axis_label = 'Year' p.yaxis.axis_label = 'Murders' # Set the range for the yaxis dynamically. Requires bokeh Rand1d object ymx = max(agg['MRD'].max(), agg['Yes'].max()) * 1.05 p.y_range=Range1d(0,ymx) p.yaxis[0].formatter = NumeralTickFormatter(format='0,0') # Actually plot the lines now. p.line('Year','MRD',source=source, line_width=3,) p.line('Year','Yes',source=source, line_width=3, color='orange') p.title.text = '{} Murders by Year'.format(states.value) # dynamic title return p
def create_figure(): ''' The main function to aggregate the data and create the figure. ''' use_df = select_state() # Get the filtered dataframe agg = use_df.groupby('YEAR', as_index=False).sum() # aggregate the dataframe agg['Clearance_Rate'] = agg['CLR'] / agg[ 'MRD'] # Set Clearance Rate column source = ColumnDataSource(agg) # put into a bokeh data structure hover = HoverTool( # Set the hover tools, ('Title', '@Column{formatting}'') tooltips=[('Year', '@YEAR'), ('Total Murders', '@MRD{0,0}'), ('Solved Murders', '@CLR{0,0}'), ('Clearance Rate', '@Clearance_Rate{0%}')]) tools = [hover] p = figure(plot_width=600, plot_height=400, tools=tools) # Create figure p.xaxis.axis_label = 'Year' p.yaxis.axis_label = 'Murders' # Set the range for the yaxis dynamically. Requires bokeh Rand1d object p.y_range = Range1d(0, agg['MRD'].max() * 1.05) p.yaxis[0].formatter = NumeralTickFormatter(format='0,0') # Actually plot the lines now. p.line( 'YEAR', 'MRD', source=source, line_width=3, ) p.line('YEAR', 'CLR', source=source, line_width=3, color='orange') p.title.text = '{} Murders by Year'.format(states.value) # dynamic title return p
def plot_volume(self, data: bt.AbstractDataBase, alpha=1.0, extra_axis=False): """extra_axis displays a second axis (for overlay on data plotting)""" source_id = FigureEnvelope._source_id(data) self._add_columns([(source_id + 'volume', np.float64), (source_id + 'colors_volume', np.object)]) kwargs = { 'fill_alpha': alpha, 'line_alpha': alpha, 'name': 'Volume', 'legend_label': 'Volume' } ax_formatter = NumeralTickFormatter(format=self._scheme.number_format) if extra_axis: source_data_axis = 'axvol' self.figure.extra_y_ranges = { source_data_axis: DataRange1d( range_padding=1.0 / self._scheme.volscaling, start=0, ) } # use colorup ax_color = convert_color(self._scheme.volup) ax = LinearAxis(y_range_name=source_data_axis, formatter=ax_formatter, axis_label_text_color=ax_color, axis_line_color=ax_color, major_label_text_color=ax_color, major_tick_line_color=ax_color, minor_tick_line_color=ax_color) self.figure.add_layout(ax, 'left') kwargs['y_range_name'] = source_data_axis else: self.figure.yaxis.formatter = ax_formatter vbars = self.figure.vbar('index', get_bar_width(), f'{source_id}volume', 0, source=self._cds, fill_color=f'{source_id}colors_volume', line_color="black", **kwargs) # make sure the new axis only auto-scales to the volume data if extra_axis: self.figure.extra_y_ranges['axvol'].renderers = [vbars] self._hoverc.add_hovertip( "Volume", f"@{source_id}volume{{({self._scheme.number_format})}}", data)
def _create_price_and_volume_histogram( # pylint: disable=too-many-arguments data, price="close", volume="volume", bins=150, color=GRAY, alpha=0.5): formatter = NumeralTickFormatter(format="0,0") hist = np.histogram(data[price], bins=bins, weights=data[volume]) hist_data = zip(hist[1], hist[0]) tooltips = [ ("Price", "@{price}"), ("Volume", "@volume{0,0}"), ] hover = HoverTool(tooltips=tooltips) return (hv.Histogram(hist_data).redim(Frequency="volume", x="price").opts( xformatter=formatter, color=color, alpha=alpha, tools=["ybox_zoom", "reset", hover], default_tools=[], invert_axes=True, hooks=[set_toolbar_none], xticks=2, ))
def initPlot(self): # TODO adf 14022018, added this for bokeh workaround, remoave after fixing import warnings warnings.filterwarnings('ignore') TickFormatter self.plot = figure( plot_height=350, plot_width=750, x_axis_type='log', y_axis_type='log', title='Detector Noise', y_axis_label='h [1/\u221AHz]', x_axis_label='f [Hz]', toolbar_location='right', toolbar_sticky=False, tools="ypan, save, reset") self.setPlotYLim(self.yLo, self.yHi) self.plot.title.offset = self.plot.plot_width * (2 / 3) self.plot.yaxis.major_label_orientation = 'horizontal' #self.plot.axis.axis_label_text_font = 'italic' self.plot.axis.axis_label_text_font_size = '11pt' self.plot.axis.major_label_text_font_size = '10pt' fi = self.detector.parameters['freqrange'][0] ff = self.detector.parameters['freqrange'][1] self.scorecalculator.SetFreqRange(fi, ff) x, y, self.names = self.scorecalculator.GetNoiseCurves() self.legends = [] self.colours = {} self.lines = {} for i, yi in enumerate(y): self.colours[self.names[i]] = palette[i] # TODO: fix this, adf 14.02.2018 # the following is a workaround for a Bokeh bug which # causes lines to not be clipped at the X/Y limits # See: https://github.com/bokeh/bokeh/issues/6787 yi=np.array(yi) x=np.array(x) idxs = np.nonzero((yi<=self.yHi) & (yi>=self.yLo))[0] self.lines[self.names[i]] = self.plot.line(x[idxs], yi[idxs], color=palette[i], \ line_width=3) self.legends.append((self.names[i], [self.lines[self.names[i]]])) self.layoutLegend(self.legends) # show freq axis as 1 10 ... 10k self.plot.xaxis.formatter=NumeralTickFormatter(format="0 a") self.plot.output_backend = "svg" self.budget = pywidgets.HTML( value=self.budgetMsg(), description='Warning: ', ) self.score = pywidgets.HTML( value=' ', description=' ' ) self.handle = show(self.plot, notebook_handle=True) return self.budget
def plot_volume(self, obj, alpha, extra_axis=False): src_prefix = sanitize_source_name(obj._name) df = convert_to_pandas(obj, self._start, self._end) if len(nanfilt(df.volume)) == 0: return colorup = convert_color(self._scheme.volup) colordown = convert_color(self._scheme.voldown) is_up = df.close > df.open colors = [colorup if x else colordown for x in is_up] self._add_to_cds(df.volume, src_prefix + 'volume') self._add_to_cds(colors, src_prefix + 'volume_colors') kwargs = { 'fill_alpha': alpha, 'line_alpha': alpha, 'name': 'Volume', 'legend': 'Volume' } ax_formatter = NumeralTickFormatter(format='0.000 a') if extra_axis: self.figure.extra_y_ranges = {'axvol': DataRange1d()} adapt_yranges(self.figure.extra_y_ranges['axvol'], df.volume) self.figure.extra_y_ranges['axvol'].end /= self._scheme.volscaling ax_color = colorup ax = LinearAxis(y_range_name="axvol", formatter=ax_formatter, axis_label_text_color=ax_color, axis_line_color=ax_color, major_label_text_color=ax_color, major_tick_line_color=ax_color, minor_tick_line_color=ax_color) self.figure.add_layout(ax, 'left') kwargs['y_range_name'] = "axvol" else: self.figure.yaxis.formatter = ax_formatter adapt_yranges(self.figure.y_range, df.volume) self.figure.y_range.end /= self._scheme.volscaling self.figure.vbar('datetime', get_bar_length_ms(obj) * 0.7, src_prefix + 'volume', 0, source=self._cds, fill_color=src_prefix + 'volume_colors', line_color="black", **kwargs) self._hoverc.add_hovertip("Volume", f"@{src_prefix}volume{{(0.00 a)}}")
def plot(self): bar = Bar(\ self.__table, values = blend('registrations', name = 'registrations', labels_name = 'registrations'),\ label = cat(columns = 'country', sort = False),\ stack = cat(columns = 'registrations'),\ agg = 'mean',\ title = 'Total of new registrations in European Union',\ legend = False,\ tooltips = [('Registrations', '@registrations{1,1}')]) bar._yaxis.formatter = NumeralTickFormatter(format='0,0') return bar
def plot(self): bar = Bar(\ self.__fuel_table, values = blend('percentage', name = 'percentage', labels_name = 'percentage'),\ label = cat(columns = 'fuel'),\ stack = cat(columns = 'percentage'),\ agg = 'mean',\ title = self.__title,\ legend = False,\ tooltips = [('Percentage', '@percentage{0.00%}')]) bar._yaxis.formatter = NumeralTickFormatter(format = '0%') return bar
def bokeh_wealth_chart(df): p = (df.wealth + df.cash_flow).rename('Net wealth').plot.line( show_figure=False, toolbar_location=None, hovertool_string=r"""<h4> Net wealth: </h4> £@{Net wealth}{0,0}""", panning=False, zooming=False) p.yaxis[0].formatter = NumeralTickFormatter(format='$0,0') p.xaxis.major_label_orientation = 3.14 / 5 p.legend.location = "top_left" # p.yaxis[0].formatter.use_scientific = False return p
def plotTotal(self): bar = Bar(\ self.__table, values = blend('total', name = 'total', labels_name = 'total'),\ label = cat(columns = 'fuel'),\ stack = cat(columns = 'total'),\ agg = 'mean',\ title = 'Total of CO2 emissions (by fuel type) in ' + self.__title,\ legend = False,\ tooltips = [('Total', '@total{1,1}' + ' g/km')]) bar._yaxis.formatter = NumeralTickFormatter(format = '0,0' + ' g/km') return bar
def generate_grid_scatter_plot(data_frame): y = data_frame['Diabetes_Pct'].values x1 = data_frame['Black_Pct'].values x2 = data_frame['Hispanic_Pct'].values x3 = data_frame['LowAccess_Pct'].values x4 = data_frame['HouseholdIncome'].values source = ColumnDataSource(data=dict(y=y, x1=x1, x2=x2, x3=x3, x4=x4)) TOOLS = "crosshair,wheel_zoom,reset,tap,pan,box_select" p1 = figure(tools=TOOLS, width=300, plot_height=250, x_range=(-.04, 1.08), y_range=(0, 0.21)) p1.scatter('x1', 'y', source=source, fill_alpha=0.8, line_color=None) p1.xaxis.axis_label = 'Percent Black' p1.yaxis[0].formatter = NumeralTickFormatter(format="0.0%") p1.xaxis[0].formatter = NumeralTickFormatter(format="0.0%") p2 = figure(tools=TOOLS, toolbar_location="right", width=300, plot_height=250, x_range=(-.04, 1.08), y_range=(0, 0.21)) p2.scatter('x2', 'y', source=source, fill_alpha=0.8, line_color=None) p2.xaxis.axis_label = 'Percent Hispanic' p2.yaxis[0].formatter = NumeralTickFormatter(format="0.0%") p2.xaxis[0].formatter = NumeralTickFormatter(format="0.0%") p3 = figure(tools=TOOLS, width=300, plot_height=250, x_range=(-.04, 1.08), y_range=(0, 0.21)) p3.scatter('x3', 'y', source=source, fill_alpha=0.8, line_color=None) p3.xaxis.axis_label = 'Low Access Population' p3.yaxis[0].formatter = NumeralTickFormatter(format="0.0%") p3.xaxis[0].formatter = NumeralTickFormatter(format="0.0%") p4 = figure(tools=TOOLS, width=300, plot_height=250, x_range=(9.8, 11.8), y_range=(0, 0.21)) p4.scatter('x4', 'y', source=source, fill_alpha=0.8, line_color=None) p4.xaxis.axis_label = 'Median Household Income (log scale)' p4.yaxis[0].formatter = NumeralTickFormatter(format="0.0%") plot_quad = gridplot([[p1, p2], [p3, p4]]) script, dev = components(plot_quad) return script, dev
def MonthlyGraph(): monthly_graph = figure(x_axis_label='Month', y_axis_label='Expenses', x_axis_type='datetime', sizing_mode='stretch_both', tools="hover, tap", tooltips="$name: @$name") monthly_graph.y_range.start = 0 y_formatter = NumeralTickFormatter(format='0a') # date_formatter = DatetimeTickFormatter(months=["%m/%y"]) monthly_graph.yaxis.formatter = y_formatter return monthly_graph
def get_counties_plot(data_frame): plot = Bar(data_frame, label='CTYNAME', values='TOT_POP', agg='max', plot_width=1200, plot_height=500, title='Population by County', legend=False) plot.xaxis.axis_label = 'County' plot.yaxis.axis_label = 'Population' plot.yaxis.formatter = NumeralTickFormatter(format="0a") plot.sizing_mode = 'scale_width' return plot
def plot_sma(stock): p = figure( x_axis_type="datetime", plot_width=WIDTH_PLOT, plot_height=300, title="Simple Moving Average (press the legend to hide/show lines)", tools=TOOLS, toolbar_location='above') p.line(x='date', y='SMA_5', line_width=2, color=BLUE, source=stock, legend='5 days', muted_color=BLUE, muted_alpha=0.2) p.line(x='date', y='SMA_10', line_width=2, color=ORANGE, source=stock, legend='10 days', muted_color=ORANGE, muted_alpha=0.2) p.line(x='date', y='SMA_50', line_width=2, color=PURPLE, source=stock, legend='50 days', muted_color=PURPLE, muted_alpha=0.2) p.line(x='date', y='SMA_100', line_width=2, color=BROWN, source=stock, legend='100 days', muted_color=BROWN, muted_alpha=0.2) p.legend.location = "bottom_left" p.legend.border_line_alpha = 0 p.legend.background_fill_alpha = 0 p.legend.click_policy = "mute" p.yaxis.formatter = NumeralTickFormatter(format='$ 0,0[.]000') return p
def bokeh_outcomes_chart(df): p = df.plot(kind='line', show_figure=False, toolbar_location=None, panning=False, zooming=False, plot_data_points=True, plot_data_points_size=5) p.hover.tooltips = [('year', '$index')] + list( (c, f'£@{c}' + '{0,0}') for c in df.columns) p.hover.mode = 'mouse' p.yaxis[0].formatter = NumeralTickFormatter(format='£0,0') p.xaxis.major_label_orientation = 3.14 / 5 p.legend.location = "top_left" # p.yaxis[0].formatter.use_scientific = False return p
def plot_volume(self, data: bt.feeds.DataBase, strat_clk: array, alpha, extra_axis=False): source_id = Figure._source_id(data) df = convert_to_pandas(strat_clk, data, self._start, self._end) if len(nanfilt(df.volume)) == 0: return colorup = convert_color(self._scheme.volup) colordown = convert_color(self._scheme.voldown) is_up = df.close > df.open colors = [colorup if x else colordown for x in is_up] self._add_to_cds(df.volume, f'{source_id}volume') self._add_to_cds(colors, f'{source_id}volume_colors') kwargs = {'fill_alpha': alpha, 'line_alpha': alpha, 'name': 'Volume', 'legend': 'Volume'} ax_formatter = NumeralTickFormatter(format=self._scheme.number_format) if extra_axis: self.figure.extra_y_ranges = {'axvol': DataRange1d()} adapt_yranges(self.figure.extra_y_ranges['axvol'], df.volume) self.figure.extra_y_ranges['axvol'].end /= self._scheme.volscaling ax_color = colorup ax = LinearAxis(y_range_name="axvol", formatter=ax_formatter, axis_label_text_color=ax_color, axis_line_color=ax_color, major_label_text_color=ax_color, major_tick_line_color=ax_color, minor_tick_line_color=ax_color) self.figure.add_layout(ax, 'left') kwargs['y_range_name'] = "axvol" else: self.figure.yaxis.formatter = ax_formatter adapt_yranges(self.figure.y_range, df.volume) self.figure.y_range.end /= self._scheme.volscaling self.figure.vbar('index', get_bar_width(), f'{source_id}volume', 0, source=self._cds, fill_color=f'{source_id}volume_colors', line_color="black", **kwargs) hover_target = None if self._scheme.merge_data_hovers else self.figure self._hoverc.add_hovertip("Volume", f"@{source_id}volume{{({self._scheme.number_format})}}", hover_target)
def get_states_plot(): source = AjaxDataSource(data={ 'STATE': [], 'STNAME': [], 'STUSAB': [], 'TOT_POP': [], 'TOT_MALE': [], 'TOT_FEMALE': [] }, data_url='/api/states/', mode='replace', method='GET') hover = HoverTool(tooltips=[ ("State", "@STNAME"), ("Population", "@TOT_POP"), ("Female Population", "@TOT_FEMALE"), ("Male Population", "@TOT_MALE"), ]) plot = figure( title='Population by State', plot_width=1200, plot_height=500, x_range=FactorRange(factors=get_state_abbreviations()), y_range=(0, 40000000), tools=[hover, 'tap', 'box_zoom', 'wheel_zoom', 'save', 'reset']) plot.toolbar.active_tap = 'auto' plot.xaxis.axis_label = 'State' plot.yaxis.axis_label = 'Population' plot.yaxis.formatter = NumeralTickFormatter(format="0a") plot.sizing_mode = 'scale_width' plot.vbar(bottom=0, top='TOT_POP', x='STUSAB', legend=None, width=0.5, source=source) url = "/counties/@STATE/" taptool = plot.select(type=TapTool) taptool.callback = OpenURL(url=url) return plot
def get_plot(self, df): """ Dataframe df must have columns x0, y0, x1, y1 (in this order) for coordinates bottom-left (x0, y0) and top right (x1, y1). Optionally a fifth value-column can be provided for colors Parameters ---------- df Returns ------- """ # processed = {} # for k, v in self.kwargs.items(): # if k.endswith('formatter') and isinstance(v, str) and '%' not in v: # v = NumeralTickFormatter(format=v) # processed[k] = v # if self.streaming: # processed['stream'] = self._stream #hvplots stream? https://holoviews.org/user_guide/Streaming_Data.html # plot = hv.Rectangles([(0, 0, 1, 1), (2, 3, 4, 6), (0.5, 2, 1.5, 4), (2, 1, 3.5, 2.5)]) processed = {} for k, v in self.kwargs.items(): if k.endswith('formatter') and isinstance(v, str) and '%' not in v: v = NumeralTickFormatter(format=v) processed[k] = v if self.streaming: #processed['stream'] = self._stream plot = hv.DynamicMap(hv.Rectangles, streams=[self._stream]) plot = plot.apply.opts(**self.opts) if self.opts else plot else: plot = hv.Rectangles(df) plot.opts(**self.opts) if self.opts else plot if self.selection_group or 'selection_expr' in self._param_watchers: plot = self._link_plot(plot) return plot
def plot_stock_price(stock): p = figure(plot_width=W_PLOT, plot_height=H_PLOT, tools=TOOLS, title="Stock price", toolbar_location='above') inc = stock.data['Close'] > stock.data['Open'] dec = stock.data['Open'] > stock.data['Close'] view_inc = CDSView(source=stock, filters=[BooleanFilter(inc)]) view_dec = CDSView(source=stock, filters=[BooleanFilter(dec)]) # map dataframe indices to date strings and use as label overrides p.xaxis.major_label_overrides = {i+int(stock.data['index'][0]): date.strftime('%b %d') for i, date in enumerate(pd.to_datetime(stock.data["Date"]))} p.xaxis.bounds = (stock.data['index'][0], stock.data['index'][-1]) p.segment(x0='index', x1='index', y0='Low', y1='High', color=RED, source=stock, view=view_inc) p.segment(x0='index', x1='index', y0='Low', y1='High', color=GREEN, source=stock, view=view_dec) p.vbar(x='index', width=VBAR_WIDTH, top='Open', bottom='Close', fill_color=BLUE, line_color=BLUE,source=stock,view=view_inc, name="price") p.vbar(x='index', width=VBAR_WIDTH, top='Open', bottom='Close', fill_color=RED, line_color=RED,source=stock,view=view_dec, name="price") p.legend.location = "top_left" p.legend.border_line_alpha = 0 p.legend.background_fill_alpha = 0 p.legend.click_policy = "mute" p.yaxis.formatter = NumeralTickFormatter(format='$ 0,0[.]000') p.x_range.range_padding = 0.05 p.xaxis.ticker.desired_num_ticks = 40 p.xaxis.major_label_orientation = 3.14/4 # Select specific tool for the plot price_hover = p.select(dict(type=HoverTool)) # Choose, which glyphs are active by glyph name price_hover.names = ["price"] # Creating tooltips price_hover.tooltips = [("Datetime", "@Date{%Y-%m-%d}"), ("Open", "@Open{$0,0.00}"), ("Close", "@Close{$0,0.00}"),("Volume", "@Volume{($ 0.00 a)}")] price_hover.formatters={"Date": 'datetime'} return p
def _create_normalized_price_and_volume_histogram(hist_data, color=ACCENT_COLOR, alpha=0.5): formatter = NumeralTickFormatter(format="0,0") tooltips = [ ("Price", "@{Price}{0,0.000}"), ("Volume Density", "@{VolumeDensity}{0,0.000}"), ] hover = HoverTool(tooltips=tooltips) return (hv.Histogram(hist_data).redim( Frequency="VolumeDensity", x="Price").opts( xformatter=formatter, color=color, alpha=alpha, tools=["xbox_zoom", "reset", hover, "save"], default_tools=[], ylabel="Volume Density", # invert_axes=True, # hooks=[set_toolbar_none], # xticks=2, ))
def _create_time_and_volume_histogram(data, time="time", volume="volume", color=GRAY, alpha=0.5): formatter = NumeralTickFormatter(format="0,0") hist_data = zip(data[time], data[volume]) tooltips = [ ("Time", "@{time}{%F}"), ("Volume", "@volume{0,0}"), ] hover = HoverTool(tooltips=tooltips, formatters={"@{time}": "datetime"}) return (hv.Histogram(hist_data).redim(Frequency="volume", x="time").opts( yformatter=formatter, color=color, alpha=alpha, tools=["xbox_zoom", "reset", hover], default_tools=[], hooks=[set_toolbar_none], yticks=4, ))
def plot_stock_price (stock): p = figure (plot_width=W_PLOT, plot_height=H_PLOT, tools=TOOLS, title="Stock price", toolbar_location='above') inc = stock.data['Close'] > stock.data['Open'] dec = stock.data['Open'] > stock.data['Close'] view_inc = CDSView (source=stock, filters=[BooleanFilter (inc)]) view_dec = CDSView (source=stock, filters=[BooleanFilter (dec)]) p.segment (x0='index', x1='index', y0='Low', y1='High', color=RED, source=stock, view=view_inc) p.segment (x0='index', x1='index', y0='Low', y1='High', color=GREEN, source=stock, view=view_dec) p.vbar (x='index', width=VBAR_WIDTH, top='Open', bottom='Close', fill_color=BLUE, line_color=BLUE, source=stock, view=view_inc, name="price") p.vbar (x='index', width=VBAR_WIDTH, top='Open', bottom='Close', fill_color=RED, line_color=RED, source=stock, view=view_dec, name="price") p.legend.location = "top_left" p.legend.border_line_alpha = 0 p.legend.background_fill_alpha = 0 p.legend.click_policy = "mute" # map dataframe indices to date strings and use as label overrides p.xaxis.major_label_overrides = { i + int (stock.data['index'][0]): date.strftime ('%b %d') for i, date in enumerate (pd.to_datetime (stock.data["Date"])) } p.xaxis.bounds = (stock.data['index'][0], stock.data['index'][-1]) # Add more ticks in the plot p.x_range.range_padding = 0.05 p.xaxis.ticker.desired_num_ticks = 40 p.xaxis.major_label_orientation = 3.14 / 4 p.yaxis.formatter = NumeralTickFormatter (format='$ 0,0[.]000') return p
def timing_plot(genfn): "Draw a timing plot for a prime generator function" if not check_fn(genfn): return global _lines def plot(fig, name, vals, num, dash='solid'): "Add a line with points to a plot" col = _palette[num % len(_palette)] fig.line('x', 'y', legend_label=name, source=vals, line_dash=dash, color=col) fig.scatter('x', 'y', legend_label=name, source=vals, marker='o', color=col) name = genfn.__name__ exist = None args = dict(plot_width=800, plot_height=400, toolbar_location='above', title="Timing") linfig = figure(y_range=[0, 1], x_range=DataRange1d(start=0), **args) logfig = figure(y_range=[1e-6, 1], x_range=DataRange1d(start=1), x_axis_type='log', y_axis_type='log', **args) num = 0 # add previous lines for k, v in _lines.items(): plot(linfig, k, v, num, 'dashed') plot(logfig, k, v, num, 'dashed') if k == name: exist = num num += 1 source = ColumnDataSource(data=dict(x=[], y=[])) for fig in (linfig, logfig): plot(fig, name, source, exist or num) fig.xaxis.axis_label = "Primes" fig.xaxis.formatter = NumeralTickFormatter(format='0[.]0 a') fig.xgrid.minor_grid_line_color = 'lightgrey' fig.xgrid.minor_grid_line_alpha = 0.2 fig.yaxis.axis_label = "Seconds" fig.legend.location = 'bottom_right' fig.legend.click_policy = 'hide' fig.legend.background_fill_alpha = 0.5 linfig.yaxis.formatter = BasicTickFormatter() logfig.yaxis.formatter = BasicTickFormatter(use_scientific=True, precision=0) lintab = Panel(child=linfig, title="Linear") logtab = Panel(child=logfig, title="Log") tabs = Tabs(tabs=[lintab, logtab]) handle = None if _incremental: # Incremental: show plot now, then incrementally add points handle = show(tabs, notebook_handle=True) try: genfn() combined = True except TypeError: combined = False if combined: # Generate line in one go plot_line_combined(genfn, source, handle) else: # Generator takes size, need to generate points separately plot_line_separate(genfn, source, handle) if not _incremental: # Plot not shown yet, show it now show(tabs) # save line data to show on next plot _lines[name] = source.data
def plot_volume(self, data, alpha=1.0, extra_axis=False): ''' Plot method for volume extra_axis: displays a second axis (for overlay on data plotting) ''' source_id = get_source_id(data) self.set_cds_col(source_id + 'volume') # create color columns volup = convert_color(self._scheme.volup) voldown = convert_color(self._scheme.voldown) self.set_cds_col((source_id + 'colors_volume', source_id + 'open', source_id + 'close', partial(cds_op_color, color_up=volup, color_down=voldown))) # prepare bar kwargs kwargs = { 'x': 'index', 'width': self._bar_width, 'top': source_id + 'volume', 'bottom': 0, 'fill_color': source_id + 'colors_volume', 'line_color': source_id + 'colors_volume', 'fill_alpha': alpha, 'line_alpha': alpha, 'name': 'Volume', 'legend_label': 'Volume' } # set axis ax_formatter = NumeralTickFormatter(format=self._scheme.number_format) if extra_axis: source_data_axis = 'axvol' # use colorup ax_color = convert_color(self._scheme.volup) # use only one additional axis to prevent multiple axis being added # to a single figure ax = self.figure.select_one({'name': source_data_axis}) if ax is None: # create new axis if not already available self.figure.extra_y_ranges = { source_data_axis: DataRange1d(range_padding=1.0 / self._scheme.volscaling, start=0) } ax = LinearAxis(name=source_data_axis, y_range_name=source_data_axis, formatter=ax_formatter, axis_label_text_color=ax_color, axis_line_color=ax_color, major_label_text_color=ax_color, major_tick_line_color=ax_color, minor_tick_line_color=ax_color) self.figure.add_layout(ax, self._scheme.vol_axis_location) kwargs['y_range_name'] = source_data_axis else: self.figure.yaxis.formatter = ax_formatter # append renderer self._figure_append_renderer(self.figure.vbar, **kwargs) # set hover label self._fp.hover.add_hovertip( 'Volume', f'@{source_id}volume{{({self._scheme.number_format})}}', data)
def plot_sv_alleles(annotations, aligned_regions_file): alignments = list(load_alignments(aligned_regions_file)) query_ids = sorted(list(set(a.query.id for a in alignments))) plots = [] for query_id in query_ids: alns = [a for a in alignments if a.query.id == query_id] x0 = [a.hit.start for a in alns] x1 = [a.hit.end for a in alns] y0 = [a.query.start for a in alns] y1 = [a.query.end for a in alns] min_x = min(x0 + x1) max_x = max(x0 + x1) x_range = (min_x, max_x) width = x_range[1] - x_range[0] pad = 0.1 * width x_range = (int(min_x - pad), int(max_x + pad)) colors = ["red" if a.hit.strand == '-' else "blue" for a in alns] fig = figure(width=800, height=300, x_range=x_range) fig.segment(x0, y0, x1, y1, line_color=colors, line_width=5, line_alpha=0.75, line_cap="butt") fig.title.text = query_id fig.yaxis.axis_label = "Amplicon" fig.xaxis.visible = False fig.yaxis.ticker = zooming_ticker() fig.xaxis.formatter = NumeralTickFormatter(format="0,0") fig.add_tools(hover) plots.append(fig) transcripts = transcripts_from_gffutils(annotations, next(a.hit.id for a in alns), x_range[0], x_range[1]) fig2 = gene_viz.GenePlot( dict(row_height=15, exon_color="Black", pack=True, label_horiz_position="center", label_vert_position="above", label_justify="center", label_offset=(0, -4), label_font_size="6pt", intron_width_percent=0.001)) fig2.link_x_range(fig) fig2.figure.xaxis.axis_label = next(a.hit.id for a in alns) fig2.figure.yaxis.visible = False fig2.figure.background_fill_color = "black" fig2.figure.background_fill_alpha = 0.15 fig2.transcripts = transcripts box = BoxAnnotation(left=min_x, right=max_x, fill_color='white', fill_alpha=1, level="underlay") fig2.figure.add_layout(box) for a in alns: box = BoxAnnotation( left=min([a.hit.start, a.hit.end]), right=max([a.hit.start, a.hit.end]), fill_color="red" if a.hit.strand == '-' else "blue", fill_alpha=0.25, level="underlay") fig2.figure.add_layout(box) fig2.update() plots.append(fig2.figure) if len(plots) > 0: save( gridplot(plots, ncols=1, toolbar_location="right", toolbar_options=dict(logo=None))) else: save(Div(text="No Data"))
p = figure(title=title, x_axis_type="datetime", plot_width=1200, plot_height=400, tools=TOOLS, toolbar_location='above') p.line(df_limit.index, df_limit.close, color='black') p.line(df_limit.index, df.sma_50, legend='SMA 50', color=BLUE) p.line(df_limit.index, df.SMA_100, legend='SMA 100', color=ORANGE) p.legend.location = "top_left" p.legend.border_line_alpha = 1 p.legend.background_fill_alpha = 1 p.legend.click_policy = "mute" p.yaxis.formatter = NumeralTickFormatter(format='$ 0,0[.]000') # plot candlesticks candlestick_width = get_candlestick_width(datetime_interval) p.segment(df_limit.index, df_limit.high, df_limit.index, df_limit.low, color="black") p.vbar(df_limit.index[inc], candlestick_width, df_limit.open[inc], df_limit.close[inc], fill_color="#D5E1DD", line_color="black") p.vbar(df_limit.index[dec],
const arrSum = arr => arr.reduce((a,b) => a + b, 0) var avg = arrSum(avgList) / avgList.length for (var i = 0; i < alpha.length; i++){ line_y[i] = avg } source.change.emit(); line_source.change.emit(); """) p.add_tools(bar_hover) p.add_tools(line_hover) p.sizing_mode = 'scale_width' p.background_fill_color = "#fdf6e3" p.border_fill_color = "#fdf6e3" p.yaxis[0].formatter = NumeralTickFormatter(format="$0,0") p.outline_line_color = None range_slider = RangeSlider(start=0, end=max(id_range), value=(0, max(id_range)), step=1, title="Showing IDs") range_slider.js_on_change('value', callback) # range_slider.js_on_change("value", CustomJS(code=""" # console.log('range_slider: value=' + this.value[0], this.toString()) # """)) range_slider.background = "#fdf6e3" layout = Column(p, range_slider) layout.sizing_mode = "scale_width" # show the results