def __init__(self, tvar_name, auto_color, show_xaxis=False, interactive=False): self.tvar_name = tvar_name self.auto_color = auto_color self.show_xaxis = show_xaxis if 'show_all_axes' in pytplot.tplot_opt_glob: if pytplot.tplot_opt_glob['show_all_axes']: self.show_xaxis = True self.interactive = interactive # Variables needed across functions self.colors = [ 'black', 'red', 'green', 'navy', 'orange', 'firebrick', 'pink', 'blue', 'olive' ] self.lineglyphs = [] self.linenum = 0 self.interactive_plot = None self.fig = Figure(x_axis_type='datetime', tools=pytplot.tplot_opt_glob['tools'], y_axis_type=self._getyaxistype()) self.fig.add_tools(BoxZoomTool(dimensions='width')) self._format()
def _set_tools(self): wheel_zoom = WheelZoomTool() pan = PanTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() crosshair = CrosshairTool() tap = TapTool() save = SaveTool() reset = ResetTool() self.lasso_select = LassoSelectTool( renderers=self.circles, # default = all available renderers select_every_mousemove=False, # to enhance performance ) self.lasso_select.overlay.line_alpha=0.9 self.lasso_select.overlay.line_color="black" self.lasso_select.overlay.fill_alpha=0.2 self.lasso_select.overlay.fill_color="grey" hover = self._get_hover_tool() self.tools = ( pan, box_zoom, self.lasso_select, box_select, crosshair, save, reset, tap, wheel_zoom ) self.plot.add_tools(*self.tools)
def plot_daily_income_per_month(income_summary, page_obj, freq='daily'): title = page_obj.object_list[0] colors = ["#c9d9d3", "#718dbf", "#e84d60"] stacks = list(income_summary.columns.drop('Total')) if freq == 'monthly': income_summary.index = [ hf.first_day_of_month(x) for x in income_summary.index ] income_summary.index = income_summary.index.rename('date') source = ColumnDataSource(income_summary) plot = figure(title=title, plot_width=500, plot_height=400, x_axis_type="datetime") renderers = plot.varea_stack(stacks, x='date', source=source, color=colors[:len(stacks)], legend=[x + ' ' for x in stacks]) plot.legend.location = 'top_left' plot.left[0].formatter.use_scientific = False plot.add_tools(BoxZoomTool()) plot.add_tools(ResetTool()) hover = HoverTool(tooltips=[('Date', '@date')]) plot.add_tools(hover) script, div = components(plot) return script, div
class GeoPlot(ElementPlot): """ Plotting baseclass for geographic plots with a cartopy projection. """ default_tools = param.List(default=['save', 'pan', 'wheel_zoom', BoxZoomTool(match_aspect=True), 'reset'], doc="A list of plugin tools to use on the plot.") show_grid = param.Boolean(default=False, doc=""" Whether to show gridlines on the plot.""") def __init__(self, element, **params): super(GeoPlot, self).__init__(element, **params) self.geographic = is_geographic(self.hmap.last) def get_extents(self, element, ranges): """ Subclasses the get_extents method using the GeoAxes set_extent method to project the extents to the Elements coordinate reference system. """ extents = super(GeoPlot, self).get_extents(element, ranges) if not getattr(element, 'crs', None): return extents elif any(e is None or not np.isfinite(e) for e in extents): extents = None else: try: extents = project_extents(extents, element.crs, DEFAULT_PROJ) except: extents = None return (np.NaN,)*4 if not extents else extents
def __init__(self, tvar_name, auto_color=False, show_xaxis=False, interactive=False, y_axis_type='log'): self.tvar_name = tvar_name self.show_xaxis = show_xaxis self.interactive = interactive #Variables needed across functions self.fig = None self.colors = [] self.lineglyphs = [] self.linenum = 0 self.zscale = 'log' self.zmin = 0 self.zmax = 1 self.callback = None self.interactive_plot = None self.fig = Figure(x_axis_type='datetime', tools=pytplot.tplot_opt_glob['tools'], y_axis_type=self._getyaxistype()) self.fig.add_tools(BoxZoomTool(dimensions='width')) self._format()
def ridgeplot(courses_obj): # first format 'courses_obj' into 'probly' DataFrame format # courses_obj: [{'course_name': 'Calculus...', ...}, ...] grades = [[100*y[2]/y[3] for y in x['assignments']] for x in courses_obj] # turn this list of lists into a complete NumPy array length = len(sorted(grades, key=len, reverse=True)[0]) grades = np.array([xi+[None]*(length-len(xi)) for xi in grades], dtype='float') columns = [x['course_name'] for x in courses_obj] grades = grades.transpose() probly = pd.DataFrame(grades, columns=columns) cats = list(reversed(probly.keys())) palette = [cc.rainbow[i*15] for i in range(17)] x = np.linspace(-20,110, 500) source = ColumnDataSource(data=dict(x=x)) p = figure(y_range=cats, plot_width=900, plot_height = 300, x_range=(-5, 120))#, toolbar_location=None) for i, cat in enumerate(reversed(cats)): adjusted = probly[cat].replace([np.inf, -np.inf], np.nan).dropna(how="all") if adjusted.size == 1 or pd.unique(adjusted).size == 1: # this means we can't compute continue pdf = gaussian_kde(adjusted) #p = figure(plot_width=400, plot_height=400) #p.line(x, pdf(x)) y = ridge(cat, pdf(x), scale=2) #p.line(x, y, color='black') #show(p) source.add(y, cat) p.patch('x', cat, color=palette[i], alpha=0.6, line_color="black", source=source) p.outline_line_color = None p.background_fill_color = "#efefef" p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()] ticks = list(np.array([np.array([0,3,7])+i*10 for i in range(10)]).flatten()) + [100] p.xaxis.ticker = FixedTicker(ticks=ticks) p.xaxis.formatter = PrintfTickFormatter(format="%d") p.xaxis.axis_label = "Your Grade Distribution" p.yaxis.axis_label = "Your Courses" p.ygrid.grid_line_color = None p.xgrid.grid_line_color = "Grey" p.xgrid.ticker = p.xaxis[0].ticker p.axis.minor_tick_line_color = None p.axis.major_tick_line_color = None p.axis.axis_line_color = None p.y_range.range_padding = 0.12 return p
class GeoPlot(ElementPlot): """ Plotting baseclass for geographic plots with a cartopy projection. """ default_tools = param.List( default=[ 'save', 'pan', 'wheel_zoom', BoxZoomTool(match_aspect=True), 'reset' ], doc="A list of plugin tools to use on the plot.") show_grid = param.Boolean(default=False, doc=""" Whether to show gridlines on the plot.""") def __init__(self, element, **params): super(GeoPlot, self).__init__(element, **params) self.geographic = is_geographic(self.hmap.last) def _axis_properties(self, axis, key, plot, dimension=None, ax_mapping={ 'x': 0, 'y': 1 }): axis_props = super(GeoPlot, self)._axis_properties(axis, key, plot, dimension, ax_mapping) if self.geographic: dimension = 'lon' if axis == 'x' else 'lat' axis_props['ticker'] = MercatorTicker(dimension=dimension) axis_props['formatter'] = MercatorTickFormatter( dimension=dimension) return axis_props def get_extents(self, element, ranges): """ Subclasses the get_extents method using the GeoAxes set_extent method to project the extents to the Elements coordinate reference system. """ extents = super(GeoPlot, self).get_extents(element, ranges) if not getattr(element, 'crs', None) or not self.geographic: return extents elif any(e is None or not np.isfinite(e) for e in extents): extents = None else: try: extents = project_extents(extents, element.crs, DEFAULT_PROJ) except: extents = None return (np.NaN, ) * 4 if not extents else extents
def _set_tools(self): wheel_zoom = WheelZoomTool() pan = PanTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() crosshair = CrosshairTool() tap = TapTool() save = SaveTool() lasso_select = LassoSelectTool( select_every_mousemove=False, # enhance performance ) code = """ var projections = require("core/util/projections"); var x = special_vars.x var y = special_vars.y var coords = projections.wgs84_mercator.inverse([x, y]) return coords[%d].toFixed(2) """ tooltips = ''' <style> .bk-tooltip>div:not(:nth-child(-n+5)) {{ display:none; }} .bk-tooltip>div {{ background-color: #dff0d8; padding: 5px; }} </style> <b>STATION: </b> @{STNNBR} <br /> <b>LON: </b> @X_WMTS{custom} <br /> <b>LAT: </b> @Y_WMTS{custom} <br /> ''' hover = HoverTool(toggleable=True, mode='mouse', tooltips=tooltips, renderers=[self.env.wmts_map_scatter], formatters={ 'X_WMTS': CustomJSHover(code=code % 0), 'Y_WMTS': CustomJSHover(code=code % 1), }) tools = (pan, box_zoom, lasso_select, hover, crosshair, tap, wheel_zoom) self.env.wmts_map.add_tools(*tools) # set defaults self.env.wmts_map.toolbar.active_drag = pan self.env.wmts_map.toolbar.active_inspect = [crosshair, hover] self.env.wmts_map.toolbar.active_scroll = wheel_zoom self.env.wmts_map.toolbar.active_tap = None
def workloadplot(courses_obj, is_ridge=True): # we just need to first get a list of lists of dicts # each sublist is a separate course # within each sublist you're gonna have a bunch of datetimes # for each datetime, you want to repeat it depending on the category datetimes = [[[xi[5]]*repeat(xi[1].lower()) for xi in x['assignments']] for x in courses_obj] datetimes = [list(itertools.chain.from_iterable(x)) for x in datetimes] datetimes = pd.DataFrame(datetimes, index=[x['course_name'] for x in courses_obj]).transpose() datetimes = datetimes.apply(pd.to_datetime) # convert to datetime datetimes = pd.DataFrame([datetimes[x].dt.week for x in datetimes]) counts = pd.DataFrame([datetimes[x].value_counts() for x in datetimes]).transpose() #counts = # use something like a[0].combine(pd.Series([0 for x in range(50)]), lambda x1, x2: x1 if type(x1)==type(pd.to_datetime('8/8/2018')) else pd.to_datetime('1/1/2018' )) assert(datetimes.shape[1] == len(courses_obj)) # for each course, need a list where each element is the number of assignments # due that week (by index) first_date = time.mktime(datetimes.apply(min).min().timetuple()) last_date = time.mktime(datetimes.apply(max).max().timetuple()) x = np.arange(first_date, last_date+DIVISION, TWO_WEEKS) x_ = np.linspace(0,101,2) source = ColumnDataSource(data=dict(x_=x_)) cats = list(datetimes.keys()) p.outline_line_color = None p.background_fill_color = "#efefef" p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()] p.xaxis.axis_label = "Your Workload Over Time" p.yaxis.axis_label = "Your Courses" p.ygrid.grid_line_color = None p.xgrid.grid_line_color = "Grey" #ticks = ['Beginning', 'End'] #p.xaxis.ticker = FixedTicker(ticks=ticks) p.xgrid.ticker = p.xaxis[0].ticker p.axis.minor_tick_line_color = None p.axis.major_tick_line_color = None p.axis.axis_line_color = None p.y_range.range_padding = 0.8 #p.y_range.group_padding = 3 return p
def gradesplot(course_obj): assignment_array = course_obj['assignments'] assignment_array.reverse() all_categories = get_categories(assignment_array) # get a list of lists # so each list within has all of the assignments belonging to that category/group data = [] for category in all_categories: category_data = [] for assignment in assignment_array: if assignment[1] == category: category_data.append(assignment) data.append(category_data) p = figure(x_axis_type="datetime", plot_width=1000, plot_height=300, y_range=(50,120)) p.title.text = "Grades over time" colors = Spectral[len(all_categories)] if len(all_categories) >= 3 else Spectral[3][:len(all_categories)] assert(len(data) == len(all_categories) == len(colors)) for datum, category, color in zip(data, all_categories, colors): df = pd.DataFrame(datum) df = df.rename({0:'name',1:'grouping', 2:'score', 3:'possible',4:'assigned',5:'due'}, axis='columns') df['due'] = pd.to_datetime(df['due']) source = ColumnDataSource(data=dict( x=df['due'], y=100*df['score']/df['possible'], category=df['grouping'], name=df['name'] )) p.line('x', 'y', line_width=2, color=color, source=source, legend=category, tags=[category]) p.circle('x', 'y', color=color, legend=category, source=source, tags=[category]) p.ygrid.grid_line_alpha = 0.75 p.ygrid.grid_line_color = "Black" p.legend.location = "bottom_left" p.legend.click_policy="hide" p.legend.label_text_font_size = '8pt' p.legend.spacing = -6 p.toolbar.logo = None p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()] hover = p.select(dict(type=HoverTool)) hover.tooltips = """ <style> .bk-tooltip>div:not(:first-child) {display:none;} </style> <span style="font-size: 12px;">@name</span> <span style="font-size: 10px;"> (@category) <br> Grade: @y%</span> """ return p
def create_bar_chart(data, title, x_name, y_name, hover_tool=None, width=1100, height=400): """Creates a bar chart plot with the exact styling for the centcom dashboard. Pass in data as a dictionary, desired plot title, name of x axis, y axis and the hover tool HTML. """ source = ColumnDataSource(data) xdr = FactorRange(factors=list(data[x_name])) ydr = Range1d(start=0, end=max(data[y_name]) * 1.05) tools = [] if hover_tool: tools = [ hover_tool, ] plot = figure(title=title, x_range=xdr, y_range=ydr, plot_width=width, plot_height=height, min_border=0, toolbar_location="above", tools=tools, outline_line_color="#666666") glyph = VBar(x=x_name, top=y_name, bottom=0, width=.8, fill_color="#ffdf00") plot.add_glyph(source, glyph) plot.add_tools(WheelZoomTool()) plot.add_tools(BoxZoomTool()) plot.add_tools(ZoomOutTool()) xaxis = LinearAxis() yaxis = LinearAxis() plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) plot.toolbar.logo = None plot.min_border_top = 0 plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = "#999999" plot.yaxis.axis_label = "Weight" plot.ygrid.grid_line_alpha = 0.1 plot.xaxis.axis_label = "Grouping" plot.xaxis.major_label_orientation = 1 return plot
def _set_tools(self): wheel_zoom = WheelZoomTool() pan = PanTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() crosshair = CrosshairTool() tap = TapTool() save = SaveTool() reset = ResetTool() # TODO: add only to one plot, maybe with n_plot self.lasso_select = LassoSelectTool( renderers=self.circles, # default all available renderers select_every_mousemove=False, # enhance performance ) tooltips = ''' <style> .bk-tooltip>div:not(:nth-child(-n+5)) {{ display:none; }} /* .bk-tooltip-custom + .bk-tooltip-custom {{ display: none; sometimes everything is hidden with this }} */ .bk-tooltip>div {{ background-color: #dff0d8; padding: 5px; }} </style> <b>INDEX: </b> @INDEX <br> <b>{x}: </b> @{x} <br> <b>{x}_FLAG_W: </b> @{x}_FLAG_W <br> <b>{y}: </b> @{y} <br> <b>{y}_FLAG_W: </b> @{y}_FLAG_W <br> '''.format(x=self.x, y=self.y) hover = HoverTool( # TODO: try to make this toggleable renderers=self.circles, toggleable=True, mode='mouse', tooltips=tooltips, ) tools = ( pan, box_zoom, self.lasso_select, box_select, crosshair, save, reset, tap, wheel_zoom ) self.plot.add_tools(*tools)
def __init__(self, tvar, auto_color, last_plot=False, interactive=False): self.tvar = tvar self.auto_color = auto_color self.last_plot = last_plot self.interactive = interactive #Variables needed across functions self.colors = [ 'black', 'red', 'green', 'navy', 'orange', 'firebrick', 'pink', 'blue', 'olive' ] self.lineglyphs = [] self.linenum = 0 self.interactive_plot = None self.fig = Figure(tools=pytplot.tplot_opt_glob['tools'], y_axis_type=self._getyaxistype()) self.fig.add_tools(BoxZoomTool(dimensions='width')) self._format()
def plot_stacked_area(df, stack_category, x_axis, colors, title='', xaxis_type=''): data = {'x_axis': x_axis} for cat in stack_category: data[cat] = list(df[cat].values) if xaxis_type == 'datetime': p = figure(x_range=x_axis, plot_height=350, title=title, toolbar_location='below', tools="pan,wheel_zoom,box_zoom,reset", tooltips="$name - @x_axis: @$name", x_axis_type='datetime') else: p = figure(x_range=x_axis, plot_height=350, title=title, toolbar_location='below', tools="pan,wheel_zoom,box_zoom,reset", tooltips="$name @x_axis: @$name") renderers = p.vbar_stack(stack_category, x="x_axis", width=0.9, color=colors, source=data, legend=[bvalue(x) for x in stack_category]) p.left[0].formatter.use_scientific = False p.add_tools(BoxZoomTool()) p.add_tools(ResetTool()) script, div = components(p) return script, div
def __create_tools(cls, **hoverkwargs): return [ TapTool(), BoxSelectTool(dimensions='width'), BoxSelectTool(dimensions='height'), BoxSelectTool(), WheelZoomTool(), BoxZoomTool(), ResetTool(), SaveTool(), HoverTool(tooltips=[('workflow', '@Workflow'), ('activity', '@Activity'), ('result', '@Result'), ('duration', '@DurationStr'), ('started', '@StartedOnTimestampStr'), ('ended', '@EndedOnTimeStampStr')], formatters={ 'started': 'printf', 'ended': 'printf' }, show_arrow=True, **hoverkwargs) ]
def visualize(self): # add axes titles ''' # Seaborn viz ax = sns.scatterplot(x = 0, y = 1, hue = 'clus_label', data = self.pca_frame) plt.title('Example Plot') plt.xlabel('PCA1') plt.ylabel('PCA2') plt.show() ''' list_x = list(self.pca_frame[0].values) list_y = list(self.pca_frame[1].values) names = self.lookup.set_index(self.index_col) names = names.reindex(index = self.pca_frame.index) names.reset_index(inplace = True) # desc = list(self.pca_frame.index.values) desc = list(names[self.name_col].values) labels = list(self.pca_frame['clus_label'].values) source = ColumnDataSource(data=dict(x=list_x, y=list_y, desc=desc, color=labels)) hover = HoverTool(tooltips=[ # ("index", "$index"), # ("(PCA1, PCA2)", "(@x, @y)"), (self.index_col, '@desc'), ]) zoom = BoxZoomTool() pan = PanTool() wheel = WheelZoomTool() mapper = LinearColorMapper(palette=plasma(256), low=min(labels), high=max(labels)) # mapper = CategoricalColorMapper(palette=plasma(256), low=min(labels), high=max(labels)) p = figure(plot_width=1000, plot_height=600, tools=[hover, zoom, pan, wheel], title="Clustering Test: " + self.index_col) p.circle('x', 'y', size=10, source=source, color=transform('color', mapper)) # fill_color arg is okay but looks worse output_file('cluster_viz_' + self.index_col + '.html') show(p)
class GeoPlot(ProjectionPlot, ElementPlot): """ Plotting baseclass for geographic plots with a cartopy projection. """ default_tools = param.List( default=[ 'save', 'pan', WheelZoomTool(**({} if bokeh_version < '0.12.16' else { 'zoom_on_axis': False })), BoxZoomTool(match_aspect=True), 'reset' ], doc="A list of plugin tools to use on the plot.") fixed_bounds = param.Boolean(default=True, doc=""" Whether to prevent zooming beyond the projections defined bounds.""") global_extent = param.Boolean(default=False, doc=""" Whether the plot should display the whole globe.""") infer_projection = param.Boolean(default=False, doc=""" Whether the projection should be inferred from the element crs.""") show_grid = param.Boolean(default=False, doc=""" Whether to show gridlines on the plot.""") show_bounds = param.Boolean(default=False, doc=""" Whether to show gridlines on the plot.""") projection = param.Parameter(default=GOOGLE_MERCATOR, doc=""" Allows supplying a custom projection to transform the axis coordinates during display. Defaults to GOOGLE_MERCATOR.""") # Project operation to apply to the element _project_operation = None _hover_code = """ var projections = require("core/util/projections"); var x = special_vars.data_x var y = special_vars.data_y var coords = projections.wgs84_mercator.inverse([x, y]) return "" + (coords[%d]).toFixed(4) """ def __init__(self, element, **params): super(GeoPlot, self).__init__(element, **params) self.geographic = is_geographic(self.hmap.last) if self.geographic and not isinstance(self.projection, (PlateCarree, Mercator)): self.xaxis = None self.yaxis = None self.show_frame = False show_bounds = self._traverse_options(element, 'plot', ['show_bounds'], defaults=False) self.show_bounds = not any(not sb for sb in show_bounds['show_bounds']) if self.show_grid: param.main.warning( 'Grid lines do not reflect {0}; to do so ' 'multiply the current element by gv.feature.grid() ' 'and disable the show_grid option.'.format( self.projection)) def _axis_properties(self, axis, key, plot, dimension=None, ax_mapping={ 'x': 0, 'y': 1 }): axis_props = super(GeoPlot, self)._axis_properties(axis, key, plot, dimension, ax_mapping) proj = self.projection if self.geographic and proj is GOOGLE_MERCATOR: dimension = 'lon' if axis == 'x' else 'lat' axis_props['ticker'] = MercatorTicker(dimension=dimension) axis_props['formatter'] = MercatorTickFormatter( dimension=dimension) return axis_props def _update_ranges(self, element, ranges): super(GeoPlot, self)._update_ranges(element, ranges) if not self.geographic: return if self.fixed_bounds: self.handles['x_range'].bounds = self.projection.x_limits self.handles['y_range'].bounds = self.projection.y_limits if self.projection is GOOGLE_MERCATOR: # Avoid zooming in beyond tile and axis resolution (causing JS errors) options = self._traverse_options(element, 'plot', ['default_span'], defaults=False) min_interval = options['default_span'][0] if options.get( 'default_span') else 5 for r in ('x_range', 'y_range'): ax_range = self.handles[r] start, end = ax_range.start, ax_range.end if (end - start) < min_interval: mid = (start + end) / 2. ax_range.start = mid - min_interval / 2. ax_range.start = mid + min_interval / 2. ax_range.min_interval = min_interval def initialize_plot(self, ranges=None, plot=None, plots=None, source=None): opts = {} if isinstance(self, HvOverlayPlot) else {'source': source} fig = super(GeoPlot, self).initialize_plot(ranges, plot, plots, **opts) if self.geographic and self.show_bounds and not self.overlaid: from . import GeoShapePlot shape = Shape(self.projection.boundary, crs=self.projection).options(fill_alpha=0) shapeplot = GeoShapePlot(shape, projection=self.projection, overlaid=True, renderer=self.renderer) shapeplot.geographic = False shapeplot.initialize_plot(plot=fig) return fig def _postprocess_hover(self, renderer, source): super(GeoPlot, self)._postprocess_hover(renderer, source) hover = self.handles.get('hover') try: from bokeh.models import CustomJSHover except: CustomJSHover = None if (not self.geographic or None in (hover, CustomJSHover) or isinstance(hover.tooltips, basestring) or self.projection is not GOOGLE_MERCATOR or hover.tooltips is None): return element = self.current_frame xdim, ydim = [dimension_sanitizer(kd.name) for kd in element.kdims] formatters, tooltips = {}, [] xhover = CustomJSHover(code=self._hover_code % 0) yhover = CustomJSHover(code=self._hover_code % 1) for name, formatter in hover.tooltips: customjs = None if formatter in ('@{%s}' % xdim, '$x'): dim = xdim customjs = xhover elif formatter in ('@{%s}' % ydim, '$y'): dim = ydim customjs = yhover if customjs: key = formatter if formatter in ('$x', '$y') else dim formatters[key] = customjs formatter += '{custom}' tooltips.append((name, formatter)) hover.tooltips = tooltips hover.formatters = formatters def get_data(self, element, ranges, style): proj = self.projection if self._project_operation and self.geographic: element = self._project_operation(element, projection=proj) return super(GeoPlot, self).get_data(element, ranges, style)
x_axis_location=None, y_axis_location=None, x_axis_type="mercator", y_axis_type="mercator", sizing_mode='scale_width', aspect_ratio=1.66, visible=True, ) tile_provider = get_provider(CARTODBPOSITRON_RETINA) map_figs[k].add_tile(tile_provider) map_figs[k].grid.grid_line_color = None map_figs[k].x_range = DataRange1d() map_figs[k].y_range = DataRange1d() bztool = BoxZoomTool(match_aspect=True) map_figs[k].add_tools(bztool) map_figs[k].toolbar.active_drag = None #bztool map_mpolys[k] = map_figs[k].multi_polygons( 'x', 'y', source=source_map, fill_color={ 'field': 'positiveIncreaseMAVPerMil', 'transform': map_color_mapper }, fill_alpha=0.6, line_color="white", line_width=1, )
class GeoPlot(ElementPlot): """ Plotting baseclass for geographic plots with a cartopy projection. """ default_tools = param.List( default=[ 'save', 'pan', WheelZoomTool(**({} if bokeh_version < '0.12.16' else { 'zoom_on_axis': False })), BoxZoomTool(match_aspect=True), 'reset' ], doc="A list of plugin tools to use on the plot.") show_grid = param.Boolean(default=False, doc=""" Whether to show gridlines on the plot.""") # Project operation to apply to the element _project_operation = None def __init__(self, element, **params): super(GeoPlot, self).__init__(element, **params) self.geographic = is_geographic(self.hmap.last) def _axis_properties(self, axis, key, plot, dimension=None, ax_mapping={ 'x': 0, 'y': 1 }): axis_props = super(GeoPlot, self)._axis_properties(axis, key, plot, dimension, ax_mapping) if self.geographic: dimension = 'lon' if axis == 'x' else 'lat' axis_props['ticker'] = MercatorTicker(dimension=dimension) axis_props['formatter'] = MercatorTickFormatter( dimension=dimension) return axis_props def _postprocess_hover(self, renderer, source): super(GeoPlot, self)._postprocess_hover(renderer, source) hover = self.handles.get('hover') try: from bokeh.models import CustomJSHover except: CustomJSHover = None if (not self.geographic or None in (hover, CustomJSHover) or isinstance(hover.tooltips, basestring)): return element = self.current_frame xdim, ydim = [dimension_sanitizer(kd.name) for kd in element.kdims] code = """ var projections = require("core/util/projections"); var x = special_vars.data_x var y = special_vars.data_y var coords = projections.wgs84_mercator.inverse([x, y]) return "" + (coords[%d]).toFixed(4) """ formatters = { xdim: CustomJSHover(formatter=code % 0), ydim: CustomJSHover(formatter=code % 1), } tooltips = [] for name, formatter in hover.tooltips: if formatter in ('@{%s}' % xdim, '@{%s}' % ydim): formatter += '{custom}' tooltips.append((name, formatter)) hover.tooltips = tooltips hover.formatters = formatters def get_extents(self, element, ranges): """ Subclasses the get_extents method using the GeoAxes set_extent method to project the extents to the Elements coordinate reference system. """ extents = super(GeoPlot, self).get_extents(element, ranges) if not getattr(element, 'crs', None) or not self.geographic: return extents elif any(e is None or not np.isfinite(e) for e in extents): extents = None else: try: extents = project_extents(extents, element.crs, DEFAULT_PROJ) except: extents = None return (np.NaN, ) * 4 if not extents else extents def get_data(self, element, ranges, style): if self._project_operation and self.geographic and element.crs != DEFAULT_PROJ: element = self._project_operation(element) return super(GeoPlot, self).get_data(element, ranges, style)
def __init__(self, dataset, parameters): self.dataset = dataset # Set up the controls self.specials = Selector( name="Specials", kind="specials", css_classes=["specials"], entries={ "Color-magnitude diagram": "cmd", "Period vs. radius": "pr", "Period vs. transit duration": "pdt", }, default="Color-magnitude diagram", ) self.data = Selector( name="Datasets", kind="datasets", css_classes=["data"], entries={"TOI Catalog": "toi", "Confirmed Planets": "confirmed"}, default="Confirmed Planets", ) self.xaxis = Selector( name="Build-Your-Own", kind="parameters", css_classes=["build-your-own"], entries=parameters, default="ra", title="X Axis", ) self.yaxis = Selector( kind="parameters", css_classes=["build-your-own"], entries=parameters, default="dec", title="Y Axis", ) self.size = Selector( name="Sides", kind="parameters", css_classes=["sides"], entries=parameters, default="dist", title="Marker Size", none_allowed=True, ) self.color = Selector( kind="parameters", css_classes=["sides"], entries=parameters, default="dist", title="Marker Color", none_allowed=True, ) # Set up the plot self.source = ColumnDataSource( data=dict(x=[], y=[], size=[], color=[]) ) self.plot = figure( plot_height=600, plot_width=700, title="", tooltips=[("TIC ID", "@ticid")], sizing_mode="scale_both", ) self.plot.circle( x="x", y="y", source=self.source, size="size", color=linear_cmap( field_name="color", palette=Viridis256, low=0, high=1 ), line_color=None, ) self.plot.add_tools( BoxSelectTool(), BoxZoomTool(), LassoSelectTool(), PanTool(), PolySelectTool(), TapTool(), WheelZoomTool(), WheelPanTool(), ZoomInTool(), ZoomOutTool(), HoverTool(), CrosshairTool(), ResetTool(), ) # Register the callback for control in [ self.specials, self.data, self.xaxis, self.yaxis, self.size, self.color, ]: control.widget.on_change("value", self.callback) # Load and display the data self.callback(None, None, None)
div = activity.loc[cat.groups["Dividends"]] bins = dates_of_interest(cadence=option, start=start, end=end) yr_bins = [] div_bins = [] for yr, value in bins.items(): mask = (div["date"] >= value["start"]) & (div["date"] <= value["end"]) div_bins.append(div.loc[mask]["netAmount"].agg(np.sum)) yr_bins.append(yr) # Categories: https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html from bokeh.models.tools import BoxZoomTool, ResetTool from bokeh.plotting import figure p = figure(x_range=yr_bins, tools=[BoxZoomTool(), ResetTool()], plot_width=800) p.vbar(x=yr_bins, top=div_bins, width=0.9) p.xgrid.grid_line_color = None p.y_range.start = 0 st.bokeh_chart(p, use_container_width=True) """ # Trade Volume """ "trades cadence:", option trades = activity.loc[cat.groups["Trades"]] # https://pandas.pydata.org/pandas-docs/stable/getting_started/comparison/comparison_with_sql.html trades.groupby("action").size()
from bokeh.models.tools import BoxZoomTool, PanTool, ResetTool from bokeh.plotting import figure, output_file, show # prepare some data x = [1, 2, 3, 4, 5] y = [4, 5, 5, 7, 2] # set output to static HTML file output_file("first_steps.html") # create a plot p = figure( title="Modifying tools example", tools=[BoxZoomTool(), ResetTool()], sizing_mode="stretch_width", max_width=500, plot_height=250, ) # add an additional pan tool # only vertical panning is allowed p.add_tools(PanTool(dimensions="width")) # add a renderer p.circle(x, y, size=10) # show the results show(p)
def create_bk_fig(x=None, xlab=None, x_min=None, x_max=None, ylab=None, fh=None, fw=None, title=None, pw=None, ph=None, x_axis_type="linear", y_axis_type="linear", x_name=None, y_name=None, **kwargs): """ Generates a bokeh figure Parameters ---------- x :obj:`DataArray` Contains x-axis data xlab : :obj:`str` X-axis label x_min : :obj:`float` Min x value x_max : :obj:`float` Max x value ylab : :obj:`str` Y-axis label fh: :obj:`int` True height of figure without legends, axes titles etc fw: :obj:`int` True width of figure without legends, axes etc title: :obj:`str` Title of plot pw: :obj:`int` Plot width including legends, axes etc ph: :obj:`int` Plot height including legends, axes etc x_axis_type: :obj:`str` Type of x-axis can be linear, log, or datetime y_axis_type: :obj:`str` Can be linear, log or datetime x_name: :obj:`str` Name of the column used for the x-axis. Mostly used to form tooltips y_name: :obj:`str` Name of the column used for the y-axis. Also used for tooltips add_grid: :obj:`bool` Whether or not to add grid add_title: :obj:`bool` Whether or not to add title to plot add_xaxis: :obj:`bool` Whether or not to add x-axis and tick marks add_yaxis: :obj:`bool` Add y-axis or not fix_plotsize: :obj:`bool` Enforce certain dimensions on plot. This is useful for ensuring a plot is not obscure by axes and other things. If activated, plot's dimensions will not be responsive. It utilises fw and fh. Returns ------- p : :obj:`Plot` A bokeh Plot object """ add_grid = kwargs.pop("add_grid", False) add_title = kwargs.pop("add_title", True) add_xaxis = kwargs.pop("add_xaxis", False) add_yaxis = kwargs.pop("add_yaxis", False) fix_plotsize = kwargs.pop("fix_plotsize", True) # addition plot specs pl_specs = kwargs.pop("pl_specs", {}) # additional axis specs ax_specs = kwargs.pop("ax_specs", {}) # ticker specs ti_specs = kwargs.pop("ti_specs", {}) plot_specs = dict(background="white", border_fill_alpha=0.1, border_fill_color="white", min_border=3, name="plot", outline_line_dash="solid", outline_line_width=2, outline_line_color="#017afe", outline_line_alpha=0.4, output_backend="canvas", sizing_mode="stretch_width", title_location="above", toolbar_location="above") plot_specs.update(pl_specs) axis_specs = dict(minor_tick_line_alpha=0, axis_label_text_align="center", axis_label_text_font="monospace", axis_label_text_font_size="10px", axis_label_text_font_style="normal", major_label_orientation="horizontal") axis_specs.update(ax_specs) tick_specs = dict(desired_num_ticks=5) tick_specs.update(ti_specs) # Define frame width and height # This is the actual size of the plot without the titles et al if fix_plotsize and not(fh or fw): fw = int(0.98 * pw) fh = int(0.93 * ph) # define the axes ranges x_range = DataRange1d(name="p_x_range", only_visible=True) y_range = DataRange1d(name="p_y_range", only_visible=True) if x_min is not None and x_max is not None and x_name.lower() in ["channel", "frequency"]: x_range = Range1d(name="p_x_range", start=x_min, end=x_max) y_range.only_visible = False # define items to add on the plot p_htool = HoverTool(tooltips=[(x_name, "$x"), (y_name, "$y")], name="p_htool", point_policy="snap_to_data") if x_name.lower() == "time": p_htool.tooltips[0] = (x_name, "$x{%d-%m-%Y %H:%M}") p_htool.formatters = {"$x": "datetime"} p_toolbar = Toolbar(name="p_toolbar", tools=[p_htool, BoxSelectTool(), BoxZoomTool(), # EditTool(), # BoxEditTool(), # RangeTool(), LassoSelectTool(), PanTool(), ResetTool(), SaveTool(), UndoTool(), WheelZoomTool()]) p_ticker = BasicTicker(name="p_ticker", **tick_specs) # select the axis scales for x and y if x_axis_type == "linear": x_scale = LinearScale(name="p_x_scale") # define the axes and tickers p_x_axis = LinearAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "datetime": x_scale = LinearScale(name="p_x_scale") # define the axes and tickers p_x_axis = DatetimeAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "log": x_scale = LogScale(name="p_x_scale") p_x_axis = LogAxis(axis_label=xlab, name="p_x_axis", ticker=p_ticker, **axis_specs) if y_axis_type == "linear": y_scale = LinearScale(name="p_y_scale") # define the axes and tickers p_y_axis = LinearAxis(axis_label=ylab, name="p_y_axis", ticker=p_ticker, **axis_specs) elif x_axis_type == "datetime": y_scale = LinearScale(name="p_y_scale") # define the axes and tickers p_y_axis = DatetimeAxis(axis_label=xlab, name="p_y_axis", ticker=p_ticker, **axis_specs) elif y_axis_type == "log": y_scale = LogScale(name="p_y_scale") # define the axes and tickers p_y_axis = LogAxis(axis_label=ylab, name="p_y_axis", ticker=p_ticker, **axis_specs) # Create the plot object p = Plot(plot_width=pw, plot_height=ph, frame_height=fh, frame_width=fw, toolbar=p_toolbar, x_range=x_range, x_scale=x_scale, y_range=y_range, y_scale=y_scale, **plot_specs) if add_title: p_title = Title(align="center", name="p_title", text=title, text_font_size="24px", text_font="monospace", text_font_style="bold",) p.add_layout(p_title, "above") if add_xaxis: p.add_layout(p_x_axis, "below") if add_yaxis: p.add_layout(p_y_axis, "left") if add_grid: p_x_grid = Grid(dimension=0, ticker=p_ticker) p_y_grid = Grid(dimension=1, ticker=p_ticker) p.add_layout(p_x_grid) p.add_layout(p_y_grid) return p
def plot(): # Read data as if uploaded file is now used, Data set 1 data1 = read_csv('app/static/uploads/Data1.csv', sep=',', skipinitialspace=1) xdata1 = data1.values[:,1] # Extract Data ydata1 = data1.values[:,2] colour1 = ['black']*len(xdata1) # Read data as if uploaded file is now used, Data set 2 data2 = read_csv('app/static/uploads/Data2.csv', sep=',', skipinitialspace=1) xdata2 = data2.values[:,1] ydata2 = data2.values[:,2] colour2 = ['green']*len(xdata2) # Read data as if uploaded file is now used, Data set 3 data3 = read_csv('app/static/uploads/Data3.csv', sep=',', skipinitialspace=1) xdata3 = data3.values[:,1] ydata3 = data3.values[:,2] colour3 = ['red']*len(xdata3) # Prepare Data3 # xdata3 = linspace(0, 100, 10) # ydata3 = sin(10*xdata3) # Data_pandas = DataFrame({'Time': xdata3, # 'Value': ydata3}) # Data_pandas.to_csv('app/static/uploads/Data3.csv') # Assign read data to ColumnDataSource objects sourceData1 = ColumnDataSource(data=dict(x=xdata1, y=ydata1, color=colour1)) sourceData2 = ColumnDataSource(data=dict(x=xdata2, y=ydata2, color=colour2)) sourceData3 = ColumnDataSource(data=dict(x=xdata3, y=ydata3, color=colour3)) my_plot = figure(tools=[BoxSelectTool(dimensions=['width'], select_every_mousemove=True), PanTool(), ResetTool(), WheelZoomTool(), BoxZoomTool()], title='Time series data', x_range=(xdata1.min(), xdata1.max()), y_range=(ydata1.min(), ydata1.max()), width=1200) # Create figure object; DEBUG: select_every_mousemove=False my_plot.extra_y_ranges = {# 'Data1': Range1d(start=ydata1.min(), end=ydata1.max()), 'Data2': Range1d(start=ydata2.min(), end=ydata2.max()), 'Data3': Range1d(start=ydata3.min(), end=ydata3.max())} my_plot.circle(x='x', y='y', color='color', source=sourceData1, size=8, alpha=0.8, legend='Data 1') # Add circle elements (glyphs) to the figure my_plot.circle(x='x', y='y', color='color', source=sourceData2, size=5, alpha=0.8, y_range_name='Data2', legend='Data 2') my_plot.circle(x='x', y='y', color='color', source=sourceData3, size=8, alpha=0.5, y_range_name='Data3', legend='Data 3') my_plot.line(x='x', y='y', color='red', source= sourceData3, alpha=0.5, y_range_name='Data3', legend='Data 3') sourceFit = ColumnDataSource(data=dict(xfit=[], yfit=[])) my_plot.circle(x='xfit', y='yfit', source=sourceFit, color='orange', alpha=0.3) # my_plot.add_layout(LinearAxis(y_range_name='Data1', axis_line_color=colour1[0]), 'left') my_plot.add_layout(LinearAxis(y_range_name='Data2', axis_line_color=colour2[0], axis_line_width=3), 'left') my_plot.add_layout(LinearAxis(y_range_name='Data3', axis_line_color=colour3[0], axis_line_width=3), 'left') # sourceAnnotate = ColumnDataSource(data=dict(text=['Foo', 'Bah'], x=[50, 50], y=[0.5, 0], x_offset=[0,0], y_offset=[0,0], text_font_size=['15pt', '15pt'], # text_color=['orange', 'orange'])) # my_plot.text(source=sourceAnnotate, text='text', x='x', y='y', x_offset='x_offset', y_offset='y_offset', text_font_size='text_font_size', text_color='text_color') sourceData1.callback = CustomJS(args=dict(sourceFit=sourceFit), code=("""FirstOrderEyeball(cb_obj, sourceFit)""")) # sourceData.callback = CustomJS(args=dict(sourceFit=sourceFit, sourceAnnotate=sourceAnnotate), code=("""FirstOrderEyeball(cb_obj, sourceFit, sourceAnnotate)""")) script, div = components(my_plot) # Break figure up into component HTML to be added to template return render_template("int_scatter.html", myScript=script, myDiv=div)
from bokeh.models.sources import ColumnDataSource from bokeh.models import Range1d, Legend, NumeralTickFormatter, DatetimeTickFormatter, Title from bokeh.models.tools import PanTool, BoxZoomTool, WheelZoomTool, ResetTool, HoverTool from bokeh.layouts import row from bokeh.palettes import Dark2 import datetime import psycopg2 import pandas as pd import numpy as np # Interactive tools to use hover = HoverTool(tooltips=[('Stock Name', '@stock_name'), ('Time', '@timestamp'), ('Price', '@y')]) tools = [PanTool(), BoxZoomTool(), ResetTool(), WheelZoomTool(), hover] name_mapper = dict(NFLX='Netflix', GE='General Electric', NVDA='NVIDIA', INTC='Intel Corporation', AAPL='Apple', AMZN='Amazon') p = figure(title="STOCKSTREAMER v0.0", tools=tools, plot_width=1000, y_range=Range1d(-50, 1200), x_range=Range1d(0, 1), plot_height=680, toolbar_location='below', toolbar_sticky=False)
#------------------------------------------------------------------------------ WIDTH = 500 HEIGHT = 500 MULT_WIDTH = 3.5 MULT_HEIGHT = 1.5 MARKERS = [ "o", "v", "^", "<", ">", "1", "2", "3", "4", "8", "s", "p", "P", "*", "h", "H", "+", "x", "X", "D", "d" ] COLORS = Category20[ 19] #["red", "yellow", "blue", "green", "rosybrown","darkorange", "fuchsia", "grey", ] TOOLS = [ PanTool(), BoxZoomTool(), WheelZoomTool(), UndoTool(), RedoTool(), ResetTool(), SaveTool(), HoverTool(tooltips=[("Price", "$y"), ("Time", "$x")]) ] NAME_RESULT_SHOW_VARS = "resultat_show_variables_pi_plus_{}_pi_minus_{}.html" #------------------------------------------------------------------------------ # definitions of functions #------------------------------------------------------------------------------ #------------------------------------------------------------------------------
def make_region_plot(src, src_gene, src_tss, src_rna, fixed_yaxis=None): ''' Construct pileup plot based on src ''' # output_file(html_output) # flatten list of lists in count column of src, find max value of absolute expression frag_count_range = max( map(abs, [x for count in src.data['count'] for x in count])) if len(src_rna.data['y_plus']) > 0: rna_count_range = max(max(src_rna.data['y_plus']), max(abs(src_rna.data['y_minus']))) else: rna_count_range = 0 count_range = max(frag_count_range, rna_count_range) if fixed_yaxis: ymin = -1 * (fixed_yaxis) ymax = fixed_yaxis else: ymin = -(count_range + 1) ymax = count_range + 1 # draw blank figure of correct size with tools p = figure(y_range=(ymin, ymax), plot_width=900, plot_height=700, tools=[ BoxSelectTool(), BoxZoomTool(), PanTool(), WheelZoomTool(), SaveTool(), ResetTool() ], toolbar_location='above') legends = [] # format axis and colors p.xaxis.axis_label = 'position' p.xaxis.major_label_orientation = pi / 4 p.xaxis[0].formatter.use_scientific = False # p.xaxis[0].ticker=FixedTicker(ticks=range(start, end, 100)) p.yaxis.axis_label = 'log normalized activity' patches = p.patches(source=src, xs='position', ys='count', fill_color='color', line_color=None, alpha=0.50) legends.append( LegendItem(label='promoter activity (plus strand)', renderers=[patches], index=0)) legends.append( LegendItem(label='promoter activity (minus strand)', renderers=[patches], index=1)) # draw RNA lines if len(src_rna.data['x_minus']) > 0: plus_line = p.line(x='x_plus', y='y_plus', line_color='#528ecb', line_width=2, source=src_rna) legends.append( LegendItem(label='RNA-seq (plus strand)', renderers=[plus_line], index=0)) minus_line = p.line(x='x_minus', y='y_minus', line_color='#ef8137', line_width=2, source=src_rna) legends.append( LegendItem(label='RNA-seq (minus strand)', renderers=[minus_line], index=1)) # add second y-axis for TSS strength max_tss = max(map(abs, src_tss.data['y0'])) p.extra_y_ranges = { 'tss': Range1d(start=-(max_tss * 4), end=(max_tss * 4)) } p.add_layout(LinearAxis(y_range_name='tss', axis_label='TSS expression'), 'right') # draw vertical rectangle p.quad(top='top', bottom='bottom', left='left', right='right', color='color', source=src_tss, y_range_name='tss') # draw horizontal line for arrow p.segment(x0='x0', y0='y0', x1='x1', y1='y1', color='color', source=src_tss, line_width=4, y_range_name='tss') # center of triangle is endpoint of segment tri = p.triangle(x='x1', y='y1', size=9, angle='angle', angle_units='deg', color='color', source=src_tss, y_range_name='tss') legends.append(LegendItem(label='inactive TSS', renderers=[tri], index=9)) legends.append(LegendItem(label='active TSS', renderers=[tri], index=0)) # plot genes p.rect(x='gene_center', y='gene_center_y', width='gene_width', color='gene_color', height=10, height_units='screen', source=src_gene) p.triangle(x='tri_x', y=0, size=20, angle='angle', angle_units='deg', fill_color='gene_color', line_color=None, source=src_gene) p.text(x='gene_center', y='gene_center_y', text='gene_name', text_color='black', text_align='center', text_baseline='middle', text_font_size='10pt', source=src_gene) p.add_layout(Legend(items=legends), 'below') return p
mean.circle('waves', 'proms', color='red', source=deviation_sel_source) mean.add_layout(span) # ============================================================================= multi_plot = Plot(plot_width=800, plot_height=400, background_fill_color='silver') multi_glyph = MultiLine(xs='waves', ys='ys', line_width=2, line_color='label') multi_plot.add_glyph(spectra_visible_multi, multi_glyph) xaxis, yaxis = LinearAxis(), LinearAxis() multi_plot.add_layout(xaxis, 'below') multi_plot.xaxis.axis_label = 'Wavelength (nm)' multi_plot.add_layout(yaxis, 'left') multi_plot.yaxis.axis_label = 'Intensity (CPS)' multi_plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) multi_plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) multi_plot.add_tools(BoxZoomTool()) multi_plot.add_tools(WheelZoomTool()) multi_plot.add_tools(ResetTool()) multi_plot.add_tools(SaveTool()) multi_plot.add_layout(span) # ============================================================================= # ~~ Clustering figures # ~ labeled_materials_image: map image of predicted material labels # ~ elbow inertia vs n_materials plot # ~ varBar bar plot of pca explained variances # ============================================================================= labeled_materials_image, label_mapper = basicMap(labeled_materials, 400, 'image') # elbow = figure(x_axis_label='Number of Materials', y_axis_label='Learning Inertia', # plot_width=400, plot_height=200, toolbar_location=None) # elbow.line('num_clusters', 'inertia', source=elbow_plot)
def create_daily_res_plot(res_forecast, load_forecast): """ Graph the res injection forecast. Arguments: res_forecast (list): list of renewable energy injection forecast load_forecast (list): list of load forecast """ # Datetime range time_of_day = [] # Create x-axis # beginning of day today = datetime.datetime.today() beginning_of_day = datetime.datetime(year=today.year, month=today.month, day=today.day) for i in range(len(res_forecast)): time_of_day.append(beginning_of_day + datetime.timedelta(minutes=i * 30)) # Compute 75 percentile percentile = np.percentile(res_forecast, 75) # Initialize dictionaries normal_dict = {'x': [], 'y': [], 'percentage': []} peak_dict = {'x': [], 'y': [], 'percentage': []} for i in range(len(res_forecast)): if res_forecast[i] >= percentile: peak_dict['x'].append(time_of_day[i]) peak_dict['y'].append(res_forecast[i]) peak_dict['percentage'].append( percentage_of(res_forecast[i], load_forecast[i])) else: normal_dict['x'].append(time_of_day[i]) normal_dict['y'].append(res_forecast[i]) normal_dict['percentage'].append( percentage_of(res_forecast[i], load_forecast[i])) # Hover tool to properly display time of day and value on hover hover = HoverTool( tooltips=[("Time of day", "@x{%H:%M}"), ("Forecast Value", "@y MWh"), ("Percentage of Daily Load", "@percentage{1.11} %")], formatters={'@x': 'datetime'}, ) # Create the figure plot = figure( x_axis_label="Time of Day", y_axis_label="Megawatts Per Hour", x_axis_type='datetime', sizing_mode="stretch_width", tools=[ hover, BoxZoomTool(), ResetTool(), LassoSelectTool(), WheelZoomTool(), PanTool(), SaveTool() ], ) plot.xaxis.formatter = DatetimeTickFormatter( minutes=["%H:%M"], hours=["%H:%M"], ) # Set x-range and y-range plot.y_range = Range1d(min(res_forecast) - 200, max(res_forecast) + 100) plot.x_range = Range1d(time_of_day[0] - datetime.timedelta(minutes=5), time_of_day[-1] + datetime.timedelta(minutes=5)) # Set a grid plot.grid.minor_grid_line_color = '#eeeeee' # Set the font and style of labels plot.axis.axis_label_text_font = "raleway" plot.axis.axis_label_text_font_style = "normal" # Set the font of ticks on the axis plot.axis.major_label_text_font = "raleway" # Set the desired ticks plot.xaxis.ticker = DatetimeTicker(desired_num_ticks=24) plot.yaxis.ticker = AdaptiveTicker(desired_num_ticks=20) # Add a line plot plot.line(time_of_day, res_forecast, line_alpha=0.2, color="#264b01", line_width=1.5) # Add two circle plots one for the normal values and one for those that # are at or above the 75-percentile plot.circle('x', 'y', source=normal_dict, size=8, color="#264b01") plot.circle('x', 'y', source=peak_dict, size=15, color="#264b01") return components(plot)
cutoff = 50 order = 3 source = ColumnDataSource(data=dict( x=timepts, au=au, p1=p1, raw_lp_decim_p1=p1, p2=p2, raw_lp_decim_p2=p2)) # Create the tools for the toolbar ts_cnt = np.arange(3) cross = [CrosshairTool() for n in ts_cnt] hover = [ HoverTool(tooltips=[('time', '$x'), ('sample', '@x')]), HoverTool(tooltips=[('time', '$x'), ('val', '@p1'), ('raw', '@raw_lp_decim_p1')]), HoverTool(tooltips=[('time', '$x'), ('val', '@p2'), ('raw', '@raw_lp_decim_p2')]) ] xzoom = [BoxZoomTool(dimensions=['width']) for n in ts_cnt] xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt] xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt] xtsel = [TapTool() for n in ts_cnt] xpan = [PanTool(dimensions=['width']) for n in ts_cnt] save = [SaveTool() for n in ts_cnt] reset = [ResetTool() for n in ts_cnt] tools = [[ cross[n], hover[n], xpan[n], xzoom[n], xwzoom[n], xsel[n], xtsel[n], save[n], reset[n] ] for n in ts_cnt] data_update_in_progress = False play_all_button = Button(label='Play', button_type='success', width=60) play_all_button.on_click(play_all)