def update_data(): x, fy, ty = taylor(expr, xs, order, (-2*sy.pi, 2*sy.pi), 200) plot.title.text = "%s vs. taylor(%s, n=%d)" % (expr, expr, order) legend.items[0].label = value("%s" % expr) legend.items[1].label = value("taylor(%s)" % expr) source.data = dict(x=x, fy=fy, ty=ty) slider.value = order
def test_multiple_renderers_correctly_added_to_legend(p, source): square = p.square(x='x', y='y', legend='square', source=source) circle = p.circle(x='x', y='y', legend='circle', source=source) legends = p.select(Legend) assert len(legends) == 1 assert legends[0].items[0].renderers == [square] assert legends[0].items[0].label == value('square') assert legends[0].items[1].renderers == [circle] assert legends[0].items[1].label == value('circle')
def test_element_xaxis_bottom_bare(self): curve = Curve(range(10)).options(xaxis='bottom-bare') plot = bokeh_renderer.get_plot(curve) xaxis = plot.handles['xaxis'] self.assertEqual(xaxis.axis_label_text_font_size, value('0pt')) self.assertEqual(xaxis.major_label_text_font_size, value('0pt')) self.assertEqual(xaxis.minor_tick_line_color, None) self.assertEqual(xaxis.major_tick_line_color, None) self.assertTrue(xaxis in plot.state.below)
def test_element_yaxis_right_bare(self): curve = Curve(range(10)).options(yaxis='right-bare') plot = bokeh_renderer.get_plot(curve) yaxis = plot.handles['yaxis'] self.assertEqual(yaxis.axis_label_text_font_size, value('0pt')) self.assertEqual(yaxis.major_label_text_font_size, value('0pt')) self.assertEqual(yaxis.minor_tick_line_color, None) self.assertEqual(yaxis.major_tick_line_color, None) self.assertTrue(yaxis in plot.state.right)
def update(): try: expr = sy.sympify(text.value, dict(x=xs)) except Exception as exception: errbox.text = str(exception) else: errbox.text = "" x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200) p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.value, expr) legend.items[0].label = value("%s" % expr) legend.items[1].label = value("taylor(%s)" % expr) source.data = dict(x=x, fy=fy, ty=ty)
def _plot_bokeh(self, current_plot, show_legend=True): from bokeh import models import bokeh.plotting as bkh from bokeh.core.properties import value lst = [] row_lst = [] for plotter in self.plots: cur_plot = bkh.figure(title=plotter.title, plot_width=self.one_figsize[0] * self.BOKEH_RESIZE, plot_height=self.one_figsize[1] * self.BOKEH_RESIZE) if plotter.xlim is not None: cur_plot.x_range = models.Range1d(start=plotter.xlim[0], end=plotter.xlim[1]) if plotter.ylim is not None: cur_plot.y_range = models.Range1d(start=plotter.ylim[0], end=plotter.ylim[1]) cur_plot.title_text_font_size = value("{}pt".format(plotter.fontsize)) cur_plot.xaxis.axis_label = plotter.xlabel cur_plot.yaxis.axis_label = plotter.ylabel cur_plot.legend.orientation = 'top_right' cur_plot = plotter._plot_bokeh(cur_plot, show_legend=show_legend) if len(row_lst) >= self.columns: lst.append(row_lst) row_lst = [] row_lst.append(cur_plot) if len(row_lst) > 0: lst.append(row_lst) grid = models.GridPlot(children=lst) return grid
def _get_national_scenario_line_plot(sources, data, parameter=None, y_ticks=None, plot_width=600, grid=True, end_factor=None, y_range=None, include_bau=True): if not y_range: y_range = get_y_range(data) plot = Plot( x_range=get_year_range(end_factor), y_range=y_range, plot_width=plot_width, **PLOT_FORMATS ) plot = add_axes(plot, y_ticks, color=dark_grey, grid=grid) hit_renderers = [] line_renderers = {} if include_bau: sc = scenarios else: sc = scenarios_no_bau for scenario in sc: source = sources[scenario] line = Line( x='t', y=parameter, line_color=scenarios_colors[scenario], line_width=2, line_cap='round', line_join='round' ) circle = Circle( x='t', y=parameter, size=4, line_color=scenarios_colors[scenario], line_width=0.5, line_alpha=deselected_alpha, fill_color=scenarios_colors[scenario], fill_alpha=0.6 ) # invisible circle used for hovering hit_target = Circle( x='t', y=parameter, size=20, line_color=None, fill_color=None ) scenario_label = Text( x=value(source.data['t'][-1] + 0.8), y=value(source.data[parameter][-1] * 0.98), text=value(names[scenario]), text_color=scenarios_colors[scenario], text_font_size="8pt", ) hit_renderer = plot.add_glyph(source, hit_target) hit_renderers.append(hit_renderer) line_renderer = plot.add_glyph(source, line) line_renderers[scenario] = line_renderer plot.add_glyph(source, circle) plot.add_glyph(scenario_label) plot.add_tools(HoverTool(tooltips="@%s{0,0} (@t)" % parameter, renderers=hit_renderers)) return (plot, line_renderers)
def plot_bokeh(self, xlim=None, ylim=None, title=None, figsize=None, xlabel=None, ylabel=None, fontsize=None, show_legend=True): """ Plot data using bokeh library. Use show() method for bokeh to see result. :param xlim: x-axis range :param ylim: y-axis range :type xlim: None or tuple(x_min, x_max) :type ylim: None or tuple(y_min, y_max) :param title: title :type title: None or str :param figsize: figure size :type figsize: None or tuple(weight, height) :param xlabel: x-axis name :type xlabel: None or str :param ylabel: y-axis name :type ylabel: None or str :param fontsize: font size :type fontsize: None or int :param bool show_legend: show or not labels for plots """ global _COLOR_CYCLE_BOKEH global _BOKEH_OUTPUT_NOTEBOOK_ACTIVATED import bokeh.plotting as bkh from bokeh.models import Range1d from bokeh.core.properties import value figsize = self.figsize if figsize is None else figsize xlabel = self.xlabel if xlabel is None else xlabel ylabel = self.ylabel if ylabel is None else ylabel title = self.title if title is None else title xlim = self.xlim if xlim is None else xlim ylim = self.ylim if ylim is None else ylim fontsize = self.fontsize if fontsize is None else fontsize self.fontsize_ = fontsize self.show_legend_ = show_legend figsize = (figsize[0] * self.BOKEH_RESIZE, figsize[1] * self.BOKEH_RESIZE) if not _BOKEH_OUTPUT_NOTEBOOK_ACTIVATED: bkh.output_notebook() _BOKEH_OUTPUT_NOTEBOOK_ACTIVATED = True current_plot = bkh.figure(title=title, plot_width=figsize[0], plot_height=figsize[1]) _COLOR_CYCLE_BOKEH = itertools.cycle(COLOR_ARRAY_BOKEH) if xlim is not None: current_plot.x_range = Range1d(start=xlim[0], end=xlim[1]) if ylim is not None: current_plot.y_range = Range1d(start=ylim[0], end=ylim[1]) current_plot.title_text_font_size = value("{}pt".format(fontsize)) current_plot.xaxis.axis_label = xlabel current_plot.yaxis.axis_label = ylabel current_plot.legend.orientation = 'top_right' current_plot = self._plot_bokeh(current_plot, show_legend) bkh.show(current_plot)
def test_legend_item_with_value_label_and_different_data_sources_does_not_raise_a_validation_error(): legend_item = LegendItem() gr_1 = GlyphRenderer(data_source=ColumnDataSource()) gr_2 = GlyphRenderer(data_source=ColumnDataSource()) legend_item.label = value('label') legend_item.renderers = [gr_1, gr_2] with mock.patch('bokeh.core.validation.check.logger') as mock_logger: check_integrity([legend_item]) assert mock_logger.error.call_count == 0
def get_energy_mix_by_scenario(df, scenario, plot_width=700): plot = Plot( x_range=get_year_range(end_factor=15), y_range=Range1d(0, 4300), plot_width=plot_width, **PLOT_FORMATS ) plot = add_axes(plot, [0, 2000, 4000], color=scenarios_colors[scenario]) source = ColumnDataSource(df) for energy_mix_column in energy_mix_columns.keys(): energy_name = energy_mix_columns[energy_mix_column] parameter = '%s_%s' % (scenario, energy_mix_column) line = Line( x='t', y=parameter, line_color='black', line_width=2, line_cap='round', line_join='round', line_alpha=0.8 ) circle = Circle( x='t', y=parameter, size=4, fill_color='black', fill_alpha=0.6 ) # invisible circle used for hovering hit_target = Circle( x='t', y=parameter, size=10, line_color=None, fill_color=None ) scenario_label = Text( x=value(source.data['t'][-1] + 2), y=value(source.data[parameter][-1] - 200), text=value(energy_name), text_color='grey', text_font_size='8pt', ) hit_renderer = plot.add_glyph(source, hit_target) plot.add_tools(HoverTool(tooltips="%s - @%s{0,0} (@t)" % (energy_name, parameter), renderers=[hit_renderer])) plot.add_glyph(source, line) plot.add_glyph(source, circle) plot.add_glyph(scenario_label) return plot
def test_vbar_stack_returns_renderers(): fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ["2015", "2016", "2017"] colors = ["#c9d9d3", "#718dbf", "#e84d60"] data = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} source = ColumnDataSource(data=data) p = plt.figure() renderers = p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=source, legend=[value(x) for x in years], name=years) assert len(renderers) == 3 assert renderers[0].name == "2015" assert renderers[1].name == "2016" assert renderers[2].name == "2017"
def add_legend(self, chart_legends): """Add the legend to your plot, and the plot to a new Document. It also add the Document to a new Session in the case of server output. Args: legends(List(Tuple(String, List(GlyphRenderer)): A list of tuples that maps text labels to the legend to corresponding renderers that should draw sample representations for those labels. """ location = None if self._legend is True: location = "top_left" else: location = self._legend items = [] for legend in chart_legends: items.append(LegendItem(label=value(legend[0]), renderers=legend[1])) if location: legend = Legend(location=location, items=items) self.add_layout(legend)
def prepare_fig(fig, grid=False, tight=True, minimalist=True, xgridlines=None, ygridlines=None, **kwargs): if fig is None: if 'tools' not in kwargs: kwargs['tools'] = TOOLS if 'title_text_font_size' not in kwargs: kwargs['title_text_font_size'] = value('6pt') fig = plotting.figure(**kwargs) if minimalist: three_ticks(fig) disable_minor_ticks(fig) if tight: tight_layout(fig) if not grid: disable_grid(fig) else: if xgridlines is not None: fig.xgrid.ticker=FixedTicker(ticks=xgridlines) if ygridlines is not None: fig.ygrid.ticker=FixedTicker(ticks=ygridlines) return fig
output_file("bar_dodged.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ['2015', '2016', '2017'] data = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 3, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} source = ColumnDataSource(data=data) p = figure(x_range=fruits, y_range=(0, 10), plot_height=350, title="Fruit Counts by Year", toolbar_location=None, tools="") p.vbar(x=dodge('fruits', -0.25, range=p.x_range), top='2015', width=0.2, source=source, color="#c9d9d3", legend=value("2015")) p.vbar(x=dodge('fruits', 0.0, range=p.x_range), top='2016', width=0.2, source=source, color="#718dbf", legend=value("2016")) p.vbar(x=dodge('fruits', 0.25, range=p.x_range), top='2017', width=0.2, source=source, color="#e84d60", legend=value("2017")) p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p)
def textStamp(self, glyph=chr(0x0f0000)): '''Creates a tool that allows arbitrary Unicode text to be "stamped" on the map. Echos to all figures. :param glyph: Arbitrary unicode string, usually (but not required to be) a single character. returns: PointDrawTool with textStamp functionality. ''' starting_font_size = 15 # in pixels render_lines = [] for figure in self.figures: render_lines.append( figure.text_stamp(x="xs", y="ys", source=self.source['text_stamp' + glyph], text=value(glyph), text_font='BARC', text_color="colour", text_font_size="fontsize")) self.source['text_stamp' + glyph].js_on_change( 'data', bokeh.models.CustomJS(args=dict( datasource=self.source['text_stamp' + glyph], starting_font_size=starting_font_size, figure=self.figures[0], colourPicker=self.colourPicker, widthPicker=self.widthPicker, saveArea=self.saveArea), code=""" for(var g = 0; g < datasource.data['xs'].length; g++) { if(!datasource.data['colour'][g]) { datasource.data['colour'][g] = colourPicker.color; } if(!datasource.data['fontsize'][g]) { datasource.data['fontsize'][g] = (widthPicker.value * starting_font_size) +'px'; } //calculate initial datasize if(!datasource.data['datasize'][g]) { var starting_font_proportion = (widthPicker.value * starting_font_size)/(figure.inner_height); datasource.data['datasize'][g] = (starting_font_proportion * (figure.y_range.end - figure.y_range.start)); } } """)) self.figures[0].y_range.js_on_change( 'start', bokeh.models.CustomJS(args=dict(render_text_stamp=render_lines[0], figure=self.figures[0]), code=""" for(var g = 0; g < render_text_stamp.data_source.data['fontsize'].length; g++) { render_text_stamp.data_source.data['fontsize'][g] = (((render_text_stamp.data_source.data['datasize'][g])/ (figure.y_range.end - figure.y_range.start))*figure.inner_height) + 'px'; } render_text_stamp.glyph.change.emit(); """)) tool3 = PointDrawTool( renderers=[render_lines[0]], tags=['barc' + glyph], ) return tool3
def make_axis(axis, size, factors, dim, flip=False, rotation=0, label_size=None, tick_size=None, axis_height=35): factors = list(map(dim.pprint_value, factors)) nchars = np.max([len(f) for f in factors]) ranges = FactorRange(factors=factors) ranges2 = Range1d(start=0, end=1) axis_label = dim_axis_label(dim) axis_props = {} if label_size: axis_props['axis_label_text_font_size'] = value(label_size) if tick_size: axis_props['major_label_text_font_size'] = value(tick_size) tick_px = font_size_to_pixels(tick_size) if tick_px is None: tick_px = 8 label_px = font_size_to_pixels(label_size) if label_px is None: label_px = 10 rotation = np.radians(rotation) if axis == 'x': align = 'center' # Adjust height to compensate for label rotation height = int(axis_height + np.abs(np.sin(rotation)) * ((nchars*tick_px)*0.82)) + tick_px + label_px opts = dict(x_axis_type='auto', x_axis_label=axis_label, x_range=ranges, y_range=ranges2, plot_height=height, plot_width=size) else: # Adjust width to compensate for label rotation align = 'left' if flip else 'right' width = int(axis_height + np.abs(np.cos(rotation)) * ((nchars*tick_px)*0.82)) + tick_px + label_px opts = dict(y_axis_label=axis_label, x_range=ranges2, y_range=ranges, plot_width=width, plot_height=size) p = Figure(toolbar_location=None, **opts) p.outline_line_alpha = 0 p.grid.grid_line_alpha = 0 if axis == 'x': p.yaxis.visible = False axis = p.xaxis[0] if flip: p.above = p.below p.below = [] p.xaxis[:] = p.above else: p.xaxis.visible = False axis = p.yaxis[0] if flip: p.right = p.left p.left = [] p.yaxis[:] = p.right axis.major_label_orientation = rotation axis.major_label_text_align = align axis.major_label_text_baseline = 'middle' axis.update(**axis_props) return p
line_t = Line(x="x", y="ty", line_color="red", line_width=2) line_t_glyph = plot.add_glyph(source, line_t) plot.add_layout(line_t_glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') xgrid = Grid(dimension=0, ticker=xaxis.ticker) ygrid = Grid(dimension=1, ticker=yaxis.ticker) legend = Legend(location="top_right") legend.items = [ LegendItem(label=value("%s" % expr), renderers=[line_f_glyph]), LegendItem(label=value("taylor(%s)" % expr), renderers=[line_t_glyph]), ] plot.add_layout(legend) def on_slider_value_change(attr, old, new): global order order = int(new) update_data() def on_text_value_change(attr, old, new): global expr try: expr = sy.sympify(new, dict(x=xs)) except Exception as exception:
#output_file('折扣商品数量.html') p1 = figure(x_range=lst_brand, plot_width=900, plot_height=350, title='各个品牌参与双十一活动的商品数量分布', tools=[hover1, 'reset, xwheel_zoom, pan, crosshair']) # 构建绘图空间 p1.vbar_stack(stackers=lst_type, x='brand', source=source1, width=0.9, color=colors, alpha=0.8, legend=[value(x) for x in lst_type], muted_color='black', muted_alpha=0.2) # 绘制堆叠图 p1.xgrid.grid_line_color = None p1.axis.minor_tick_line_color = None p1.outline_line_color = None p1.legend.location = "top_right" p1.legend.orientation = "horizontal" p1.legend.click_policy = "mute" # 设置其他参数 show(p1) data1_brands = result2.copy()
text = Text(x="dates", y="times", text="texts", text_align="center") plot.add_glyph(text_source, text) xformatter = DatetimeTickFormatter(months="%b %Y") xaxis = DatetimeAxis(formatter=xformatter) plot.add_layout(xaxis, 'below') yaxis = DatetimeAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) legend = Legend(items=[ LegendItem(label=value('sunrise'), renderers=[sunrise_line_renderer]), LegendItem(label=value('sunset'), renderers=[sunset_line_renderer]) ]) plot.add_layout(legend) doc = Document() doc.add_root(plot) if __name__ == "__main__": doc.validate() filename = "daylight.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Daylight Plot")) print("Wrote %s" % filename) view(filename)
def assembly_chart(df, complements): """function to assembly the chart""" print('starting the plot...') # specify the output file name output_file("movigrama_chart.html") # force to show only one plot when multiples executions of the code occur # otherwise the plots will append each time one new calling is done reset_output() # create ColumnDataSource objects directly from Pandas data frames source = ColumnDataSource(df) # use the column DT as index df.set_index('DT', inplace=True) ########################################################################### # # Movigrama Plot # ########################################################################### # build figure of the plot p = figure(x_axis_type='datetime', x_axis_label='days of moviment', y_axis_label='unities movimented', plot_width=1230, plot_height=500, active_scroll='wheel_zoom') # TODO Specify X range (not all plots have 365 days of moviment) # build the Stock Level bar r1 = p.vbar(x='DT', bottom=0, top='STOCK', width=pd.Timedelta(days=1), fill_alpha=0.4, color='paleturquoise', source=source) # build the OUT bar p.vbar(x='DT', bottom=0, top='SOMA_SAI', width=pd.Timedelta(days=1), fill_alpha=0.8, color='crimson', source=source) # build the IN bar p.vbar(x='DT', bottom=0, top='SOMA_ENTRA', width=pd.Timedelta(days=1), fill_alpha=0.8, color='seagreen', source=source) # edit title # adds warehouse title p.add_layout( Title(text=complements['warehouse'], text_font='helvetica', text_font_size='10pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="italic"), 'above') # adds product title p.add_layout( Title(text=complements['product'], text_font='helvetica', text_font_size='10pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="italic"), 'above') # adds main title p.add_layout( Title(text='Movigrama Endicon', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.9, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p.renderers.extend([hline]) # adapt the range to the plot p.x_range.range_padding = 0.1 p.y_range.range_padding = 0.1 # format the plot's outline p.outline_line_width = 4 p.outline_line_alpha = 0.1 p.outline_line_color = 'orangered' # format major labels p.axis.major_label_text_color = 'gray' p.axis.major_label_text_font_style = 'bold' # format labels p.axis.axis_label_text_color = 'gray' p.axis.axis_label_text_font_style = 'bold' # p.xgrid.grid_line_color = None # disable vertical bars # p.ygrid.grid_line_color = None # disable horizontal bars # change placement of minor and major ticks in the plot p.axis.major_tick_out = 10 p.axis.minor_tick_in = -3 p.axis.minor_tick_out = 6 p.axis.minor_tick_line_color = 'gray' # format properly the X datetime axis p.xaxis.formatter = DatetimeTickFormatter(days=['%d/%m'], months=['%m/%Y'], years=['%Y']) # iniciate hover object hover = HoverTool() hover.mode = "vline" # activate hover by vertical line hover.tooltips = [("SUM-IN", "@SOMA_ENTRA"), ("SUM-OUT", "@SOMA_SAI"), ("COUNT-IN", "@TRANSACT_ENTRA"), ("COUNT-OUT", "@TRANSACT_SAI"), ("STOCK", "@STOCK"), ("DT", "@DT{%d/%m/%Y}")] # use 'datetime' formatter for 'DT' field hover.formatters = {"DT": 'datetime'} hover.renderers = [r1] # display tolltip only to one render p.add_tools(hover) ########################################################################### # # Demand analysis # ########################################################################### # change to positive values df['out_invert'] = df['SOMA_SAI'] * -1 # moving average with n=30 days df['MA30'] = df['out_invert'].rolling(30).mean().round(0) # moving standard deviation with n=30 days df['MA30_std'] = df['out_invert'].rolling(30).std().round(0) # lower control limit for 1 sigma deviation df['lcl_1sigma'] = (df['MA30'] - df['MA30_std']) # upper control limit for 1 sigma deviation df['ucl_1sigma'] = (df['MA30'] + df['MA30_std']) source = ColumnDataSource(df) p1 = figure(plot_width=1230, plot_height=500, x_range=p.x_range, x_axis_type="datetime", active_scroll='wheel_zoom') # build the Sum_out bar r1 = p1.vbar(x='DT', top='out_invert', width=pd.Timedelta(days=1), color='darkred', line_color='salmon', fill_alpha=0.4, source=source) # build the moving average line p1.line(x='DT', y='MA30', source=source) # build the confidence interval band = Band(base='DT', lower='lcl_1sigma', upper='ucl_1sigma', source=source, level='underlay', fill_alpha=1.0, line_width=1, line_color='black') p1.renderers.extend([band]) # adds title p1.add_layout( Title(text='Demand Variability', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p1.renderers.extend([hline]) # format the plot's outline p1.outline_line_width = 4 p1.outline_line_alpha = 0.1 p1.outline_line_color = 'orangered' # format major labels p1.axis.major_label_text_color = 'gray' p1.axis.major_label_text_font_style = 'bold' # format labels p1.axis.axis_label_text_color = 'gray' p1.axis.axis_label_text_font_style = 'bold' # change placement of minor and major ticks in the plot p1.axis.major_tick_out = 10 p1.axis.minor_tick_in = -3 p1.axis.minor_tick_out = 6 p1.axis.minor_tick_line_color = 'gray' # format properly the X datetime axis p1.xaxis.formatter = DatetimeTickFormatter(days=['%d/%m'], months=['%m/%Y'], years=['%Y']) # iniciate hover object hover = HoverTool() hover.mode = "vline" # activate hover by vertical line hover.tooltips = [("DEMAND", '@out_invert'), ("UCL 1σ", "@ucl_1sigma"), ("LCL 1σ", "@lcl_1sigma"), ("M AVG 30d", "@MA30"), ("DT", "@DT{%d/%m/%Y}")] # use 'datetime' formatter for 'DT' field hover.formatters = {"DT": 'datetime'} hover.renderers = [r1] # display tolltip only to one render p1.add_tools(hover) ########################################################################### # # Demand groupped by month # ########################################################################### resample_M = df.iloc[:, 0:6].resample('M').sum() # resample to month # create column date as string resample_M['date'] = resample_M.index.strftime('%b/%y').values # moving average with n=3 months resample_M['MA3'] = resample_M['out_invert'].rolling(3).mean() resample_M['MA3'] = np.ceil(resample_M.MA3) # round up the column MA3 # resample to month with mean resample_M['mean'] = np.ceil(resample_M['out_invert'].mean()) # resample to month with standard deviation resample_M['std'] = np.ceil(resample_M['out_invert'].std()) # moving standard deviation with n=30 days resample_M['MA3_std'] = np.ceil(resample_M['out_invert'].rolling(3).std()) # lower control limit for 1 sigma deviation resample_M['lcl_1sigma'] = resample_M['MA3'] - resample_M['MA3_std'] # upper control limit for 1 sigma deviation resample_M['ucl_1sigma'] = resample_M['MA3'] + resample_M['MA3_std'] source = ColumnDataSource(resample_M) p2 = figure(plot_width=1230, plot_height=500, x_range=FactorRange(factors=list(resample_M.date)), title='demand groupped by month') colors = factor_cmap('date', palette=Category20_20, factors=list(resample_M.date)) p2.vbar(x='date', top='out_invert', width=0.8, fill_color=colors, fill_alpha=0.8, source=source, legend=value('OUT')) p2.line(x='date', y='MA3', color='red', line_width=3, line_dash='dotted', source=source, legend=value('MA3')) p2.line(x='date', y='mean', color='blue', line_width=3, line_dash='dotted', source=source, legend=value('mean')) band = Band(base='date', lower='lcl_1sigma', upper='ucl_1sigma', source=source, level='underlay', fill_alpha=1.0, line_width=1, line_color='black') labels1 = LabelSet(x='date', y='MA3', text='MA3', level='glyph', y_offset=5, source=source, render_mode='canvas', text_font_size="8pt", text_color='darkred') labels2 = LabelSet(x='date', y='out_invert', text='out_invert', level='glyph', y_offset=5, source=source, render_mode='canvas', text_font_size="8pt", text_color='gray') low_box = BoxAnnotation( top=resample_M['mean'].iloc[0] - resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='red') mid_box = BoxAnnotation( bottom=resample_M['mean'].iloc[0] - resample_M['std'].iloc[0], # analysis:ignore top=resample_M['mean'].iloc[0] + resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='green') high_box = BoxAnnotation( bottom=resample_M['mean'].iloc[0] + resample_M['std'].iloc[0], # analysis:ignore fill_alpha=0.1, fill_color='red') p2.renderers.extend([band, labels1, labels2, low_box, mid_box, high_box]) p2.legend.click_policy = "hide" p2.legend.background_fill_alpha = 0.4 p2.add_layout( Title(text='Demand Grouped by Month', text_font='helvetica', text_font_size='16pt', text_color='orangered', text_alpha=0.5, align='center', text_font_style="bold"), 'above') # adds horizontal line hline = Span(location=0, line_alpha=0.4, dimension='width', line_color='gray', line_width=3) p2.renderers.extend([hline]) # format the plot's outline p2.outline_line_width = 4 p2.outline_line_alpha = 0.1 p2.outline_line_color = 'orangered' # format major labels p2.axis.major_label_text_color = 'gray' p2.axis.major_label_text_font_style = 'bold' # format labels p2.axis.axis_label_text_color = 'gray' p2.axis.axis_label_text_font_style = 'bold' # change placement of minor and major ticks in the plot p2.axis.major_tick_out = 10 p2.axis.minor_tick_in = -3 p2.axis.minor_tick_out = 6 p2.axis.minor_tick_line_color = 'gray' # iniciate hover object # TODO develop hoverTool # hover = HoverTool() # hover.mode = "vline" # activate hover by vertical line # hover.tooltips = [("SUM-IN", "@SOMA_ENTRA"), # ("SUM-OUT", "@SOMA_SAI"), # ("COUNT-IN", "@TRANSACT_ENTRA"), # ("COUNT-OUT", "@TRANSACT_SAI"), # ("STOCK", "@STOCK")] # hover.renderers = [r1] # display tolltip only to one render # p2.add_tools(hover) ########################################################################### # # Plot figures # ########################################################################### # put the results in a column and show show(column(p, p1, p2)) # show(p) # plot action print('plot finished')
def plot_with_bokeh(self, figure_width=5, figure_height="auto", tools="auto"): """Plot the graphic record using Bokeh. Examples -------- >>> """ if not BOKEH_AVAILABLE: raise ImportError("``plot_with_bokeh`` requires Bokeh installed.") if not PANDAS_AVAILABLE: raise ImportError("``plot_with_bokeh`` requires Pandas installed.") # Set up default tools if tools == "auto": tools = [HoverTool(tooltips="@hover_html"), "xpan,xwheel_zoom,reset,tap"] # FIRST PLOT WITH MATPLOTLIB AND GATHER INFOS ON THE PLOT ax, (features_levels, plot_data) = self.plot(figure_width=figure_width) width, height = [int(100 * e) for e in ax.figure.get_size_inches()] plt.close(ax.figure) if figure_height == "auto": height = int(0.5 * height) else: height = 100 * figure_height height = max(height, 185) # Minimal height to see all icons max_y = max( [data["annotation_y"] for f, data in plot_data.items()] + list(features_levels.values()) ) # BUILD THE PLOT () plot = figure( plot_width=width, plot_height=height, tools=tools, x_range=Range1d(0, self.sequence_length), y_range=Range1d(-1, max_y + 1), ) plot.patches( xs="xs", ys="ys", color="color", line_color="#000000", source=ColumnDataSource( pd.DataFrame.from_records( [ self.bokeh_feature_patch( feature.start, feature.end, feature.strand, figure_width=figure_width, level=level, color=feature.color, label=feature.label, hover_html=( feature.html if feature.html is not None else feature.label ), ) for feature, level in features_levels.items() ] ) ), ) if plot_data != {}: if version.parse(bokeh.__version__) < version.parse("2.3"): value_arial = "arial" else: # >= 2.3 value_arial = value("arial") plot.text( x="x", y="y", text="text", text_align="center", text_font_size="12px", text_font=value_arial, text_font_style="normal", source=ColumnDataSource( pd.DataFrame.from_records( [ dict( x=feature.x_center, y=pdata["annotation_y"], text=feature.label, color=feature.color, ) for feature, pdata in plot_data.items() ] ) ), ) plot.segment( x0="x0", x1="x1", y0="y0", y1="y1", line_width=0.5, color="#000000", source=ColumnDataSource( pd.DataFrame.from_records( [ dict( x0=feature.x_center, x1=feature.x_center, y0=pdata["annotation_y"], y1=pdata["feature_y"], ) for feature, pdata in plot_data.items() ] ) ), ) plot.yaxis.visible = False plot.outline_line_color = None plot.grid.grid_line_color = None plot.toolbar.logo = None return plot
# data categories = ['category1', 'category2', 'category3'] grouped_bar_df = pd.DataFrame({'categories' : categories, '2015': [2, 1, 4], '2016': [5, 3, 3], '2017': [3, 2, 4]}) # plot grouped_bar = figure(x_range=categories, y_range=(0, 10), plot_height=250) # offsets bars / bar locations on axis dodge1 = dodge('categories', -0.25, range=grouped_bar.x_range) dodge2 = dodge('categories', 0.0, range=grouped_bar.x_range) dodge3 = dodge('categories', 0.25, range=grouped_bar.x_range) grouped_bar.vbar(x=dodge1, top='2015', width=0.2, source=grouped_bar_df, color='gray', legend=value('2015')) grouped_bar.vbar(x=dodge2, top='2016', width=0.2, source=grouped_bar_df, color='blue', legend=value('2016')) grouped_bar.vbar(x=dodge3, top='2017', width=0.2, source=grouped_bar_df, color='green', legend=value('2017')) # format legend grouped_bar.legend.location = 'top_left' grouped_bar.legend.orientation = 'horizontal' show(grouped_bar) Stacked Area Chart In [67]: stacked_area_df = pd.DataFrame({'x': [1, 2, 3, 4, 5], 'y1': [1, 2, 4, 3, 4], 'y2': [1, 4, 2, 2, 3]}) stacked_area_plot = figure(plot_width=600, plot_height=300)
def NewRegistered(): dfnr = pd.read_csv('BokehApp/Data/NewRegHouses_CLEANED.csv', delimiter=',', index_col='Year_RNH') xnr = '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018' pnr = figure(x_range=xnr, plot_height=350, plot_width=550, title='Number of new properties registered', tools='pan, wheel_zoom, box_zoom, reset') sourcenr = ColumnDataSource( data=dict(x=xnr, y=dfnr['Ireland'], y1=dfnr['Dublin'])) pnr.line(x='x', y='y', line_width=2.5, line_color='#440154', source=sourcenr, legend=value('Ireland')) pnr.line(x='x', y='y1', line_width=2.5, line_color='#FDE724', source=sourcenr, legend=value('Dublin')) pnr.circle(x='x', y='y', size=5, color='#B2DD2C', source=sourcenr, legend=value('Ireland')) pnr.circle(x='x', y='y1', size=5, color='#35B778', source=sourcenr, legend=value('Dublin')) hoverpnr = HoverTool() hoverpnr.tooltips = [('Ireland', '@y'), ('Dublin', '@y1')] pnr.add_tools(hoverpnr) pnr.legend.location = 'top_right' #pnr.y_range.range_padding = 0.02 pnr.xgrid.grid_line_color = None tick_labels_pnr = { '10000': '10K', '20000': '20K', '30000': '30K', '40000': '40K', '50000': '50K', '60000': '60K' } pnr.yaxis.major_label_overrides = tick_labels_pnr #pnr.legend.background_fill_alpha=None pnr.legend.border_line_alpha = 0 pnr.legend.label_text_font_size = "11px" pnr.legend.click_policy = "hide" pnr.title.text_font_size = '15px' #pti.axis.major_label_text_font_style = 'bold' pnr.xaxis.major_label_text_font_style = 'bold' pnr.toolbar.autohide = True return pnr
def main(): # reads df from file df = pd.read_csv('../../university_ranking.csv', index_col=0) output_file('docs/bar-chart-continent-split.html') # splits data-frame into top 800 data-frames per year df2016 = df.loc[df['year'] == 2016].head(800) df2017 = df.loc[df['year'] == 2017].head(800) df2018 = df.loc[df['year'] == 2018].head(800) dfs = [df2016, df2017, df2018] # continent order that I wanted continents = ['Europe', 'America', 'Asia', 'Oceania', 'Africa'] list = [] # all years years = ['2016', '2017', '2018'] # all continents put into lists continents_2016 = df2016['continent'].tolist() continents_2017 = df2017['continent'].tolist() continents_2018 = df2018['continent'].tolist() # all continents counter and put into dictionaries count_2016 = dict(Counter(continents_2016)) count_2017 = dict(Counter(continents_2017)) count_2018 = dict(Counter(continents_2018)) # lists of counts in corrrect order as outlined above list2016 = [count_2016[key] for key in continents] list2017 = [count_2017[key] for key in continents] list2018 = [count_2018[key] for key in continents] # dictionary with data for making a figure data = { 'continents': continents, '2016': list2016, '2017': list2017, '2018': list2018 } source = ColumnDataSource(data=data) p = figure(x_range=continents, y_range=(0, 450), plot_height=250, title="University count per continent per year", toolbar_location=None, tools="hover", tooltips='No. of univesities: @$name') p.vbar(x=dodge('continents', -0.25, range=p.x_range), top='2016', width=0.2, source=source, color="#c9d9d3", legend=value("2016"), name='2016') p.vbar(x=dodge('continents', 0.0, range=p.x_range), top='2017', width=0.2, source=source, color="#718dbf", legend=value("2017"), name='2017') p.vbar(x=dodge('continents', 0.25, range=p.x_range), top='2018', width=0.2, source=source, color="#e84d60", legend=value("2018"), name='2018') p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_right" p.legend.orientation = "horizontal" show(p)
elif row['Q47'] == 'Vrouw': d_age_s[age]['Female'] += 1 d_age_s = {str(key):d_age_s[key] for key in d_age_s} sorted_age_gender = sorted(d_age_s) output_file("participants_age_gender.html") ages = [age for age in sorted_age_gender] genders = ["Male", "Female"] colors = ["#718dbf", "#e84d60"] data = {'ages' : ages, 'Male' : [d_age_s[age]['Male'] for age in sorted_age_gender], 'Female' : [d_age_s[age]['Female'] for age in sorted_age_gender]} p = figure(x_range=ages, plot_height=500, plot_width=1000, title="Participants age per gender", toolbar_location=None, tools="") p.vbar_stack(genders, x='ages', width=0.9, color=colors, source=data, legend=[value(x) for x in genders]) p.y_range.start = 0 p.y_range.end = 80 p.x_range.range_padding = 0.01 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p)
def screen(val: float): return value(val, units="screen")
cy1="ym01", line_color="#D95F02", line_width=2)), ("ellipse", Ellipse(x="x", y="y", width=screen(15), height=screen(25), angle=-0.7, fill_color="#1D91C0")), ("image_url", ImageURL(x="x", y="y", w=0.4, h=0.4, url=value("https://static.bokeh.org/logos/logo.png"), anchor="center")), ("line", Line(x="x", y="y", line_color="#F46D43")), ("multi_line", MultiLine(xs="xs", ys="ys", line_color="#8073AC", line_width=2)), ("multi_polygons", MultiPolygons(xs="xsss", ys="ysss", line_color="#8073AC", fill_color="#FB9A99", line_width=2)), ("patch", Patch(x="x", y="y", fill_color="#A6CEE3")), ("patches", Patches(xs="xs", ys="ys", fill_color="#FB9A99")), ("quad", Quad(left="x", right="xp01", top="y", bottom="ym01", fill_color="#B3DE69")),
source = ColumnDataSource(data=data) p = figure( x_range=data['fruits'], plot_width=800, title= "Studios Industry Market Share and Percent of Films Released of Top 10 Films (2005)", toolbar_location=None, tools="") p.vbar(x=dodge('fruits', -0.25, range=p.x_range), top='2015', width=0.2, source=source, color="#c9d9d3", legend=value("Market Share (%)")) p.vbar(x=dodge('fruits', 0.0, range=p.x_range), top='2016', width=0.2, source=source, color="#718dbf", legend=value("Count of 2005 Films (%)")) p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_right" p.legend.orientation = "vertical" p.xaxis.major_label_orientation = math.pi / 2 p.title.align = 'center'
def Transactions(): df = pd.read_csv('BokehApp/Data/HT_SalesAll.csv', delimiter='\t') df.reset_index(inplace=True) df = df[['Year','Dublin New', 'Ireland New','Dublin Existing','Ireland Existing']] df.set_index('Year', inplace=True) varpti = ['Dublin New', 'Ireland New', 'Dublin Existing','Ireland Existing'] #the value of the y axis has to be in str format yearspti = '2010','2011','2012', '2013', '2014', '2015', '2016', '2017', '2018' #df3.index.values.tolist() xrange = df.values.max()*1.01 sourcepti = ColumnDataSource(data=dict(x=yearspti, y=df['Dublin New'], y1=df['Ireland New'],y2=df['Dublin Existing'], y3=df['Ireland Existing'])) pti = figure(y_range=yearspti, x_range=(0, xrange), plot_height=350, plot_width=550, title='Properties Transactions in Ireland', tools='pan, wheel_zoom, box_zoom, reset') pti.hbar(y=dodge('x', -0.2, range=pti.y_range), right='y', height=0.15, source=sourcepti, color='#440154', legend=value('Dublin New')) pti.hbar(y=dodge('x', 0, range=pti.y_range), right='y1', height=0.15, source=sourcepti, color='#30678D', legend=value('Ireland New')) pti.hbar(y=dodge('x', 0.2, range=pti.y_range), right='y2', height=0.15, source=sourcepti, color='#35B778', legend=value('Dublin Exsiting')) pti.hbar(y=dodge('x', 0.4, range=pti.y_range), right='y3', height=0.15, source=sourcepti, color='#FDE724', legend=value('Ireland Exsiting')) hoverpti = HoverTool() hoverpti.tooltips=[('Dubin New', '@y'), ('Ireland New', '@y1'), ('Dublin Existing', '@y2'), ('Ireland Existing', '@y3')] pti.add_tools(hoverpti) pti.legend.location='bottom_right' pti.y_range.range_padding = 0.02 #pti.grid.grid_line_color = None pti.grid.grid_line_alpha = 0.6 pti.grid.grid_line_dash = 'dotted' pti.grid.grid_line_dash_offset = 5 pti.grid.grid_line_width = 2 tick_labels_pti = {'10000':'10K','20000':'20K','30000':'30K','40000':'40K','50000':'50K'} pti.xaxis.major_label_overrides = tick_labels_pti pti.legend.background_fill_alpha=None pti.legend.border_line_alpha=0 pti.legend.label_text_font_size = "11px" pti.legend.click_policy="hide" pti.title.text_font_size = '15px' #pti.axis.major_label_text_font_style = 'bold' pti.xaxis.major_label_text_font_style = 'bold' pti.toolbar.autohide = True #pti.outline_line_color=None return pti
} source = ColumnDataSource(data=data) p = figure(x_range=restaurants, plot_height=250, title="Review Sentiment Counts", toolbar_location=None, tools="") p.vbar_stack(sentiments, x='restaurants', width=0.9, color=colors, source=source, legend=[value(x) for x in sentiments]) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p) output_file("sentiment_graph_2.html") # restaurants = ['wilbur_mexicana', 'celebrity_hot_pot', 'hashi_izakaya', 'kinka_izakaya', 'sushi_bong', 'uncle_tetsu'] sentiments = ["Positive", "Neutral", "Negative"]
source = ColumnDataSource(data=dict(x=[], fy=[], ty=[])) p = figure(x_range=(-7, 7), y_range=(-100, 200), width=800, height=400) line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source) line_t = p.line(x="x", y="ty", line_color="firebrick", line_width=2, source=source) p.background_fill_color = "lightgrey" legend = Legend(location="top_right") legend.items = [ LegendItem(label=value(f"{expr}"), renderers=[line_f]), LegendItem(label=value(f"taylor({expr})"), renderers=[line_t]), ] p.add_layout(legend) def update(): try: expr = sy.sympify(text.value, dict(x=xs)) except Exception as exception: errbox.text = str(exception) else: errbox.text = "" x, fy, ty = taylor(expr, xs, slider.value, (-2 * sy.pi, 2 * sy.pi), 200) p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (
source = ColumnDataSource(data=data) # create a new plot with a title y_axis range and plot height p = figure(x_range=countries, y_range=(0, 400000000), plot_height=450, title="") # creating bar charts for the top 5 movies with color codes p.vbar(x=dodge('countries', -0.34, range=p.x_range), top=top_movies[0], width=0.15, source=source, color="#c9d9d3", legend=value(top_movies[0])) p.vbar(x=dodge('countries', -0.17, range=p.x_range), top=top_movies[1], width=0.15, source=source, color="#718dbf", legend=value(top_movies[1])) p.vbar(x=dodge('countries', 0.0, range=p.x_range), top=top_movies[2], width=0.15, source=source, color="#e84d60", legend=value(top_movies[2]))
for plot, source in zip([plot_r1, plot_r2], [source_r1, source_r2]): for name, color in zip(df_r1.columns, Dark2[3]): if "Y" in name: line_width = 4 line_alpha = 0.6 else: line_width = 2 line_alpha = 1. plot.line(x='index', y=name, line_width=line_width, line_alpha=line_alpha, source=source, color=color, legend=value(name)) plot.legend.location = "top_left" plot.legend.orientation = "horizontal" plot.legend.click_policy = "hide" trial_type_a_corr = Label(x=159, y=175, x_units='screen', y_units='screen', text='Trial Type A Correlation: {corr}'.format(corr=corr_a), render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) trial_type_b_corr = Label(x=385, y=175, x_units='screen', y_units='screen', text='Trial Type B Correlation: {corr}'.format(corr=corr_b), render_mode='css', border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0)
def textStamp(self, figure): self.source_text_stamp = ColumnDataSource(data.EMPTY) self.source_text_stamp.add([], "datasize") self.source_text_stamp.add([], "fontsize") self.source_text_stamp.add([], "colour") #render_text_stamp = self.figure.circle(x="xs",y="ys",legend_label="X", source=source); starting_font_size = 30 #in pixels starting_colour = "orange" #in CSS-type spec '''glyph = bokeh.models.Text( x="xs", y="ys", text=value("🌧"), text_color="colour", text_font_size="fontsize")''' #glyph.text_font_size = '%spx' % starting_font_size #render_text_stamp = self.figure.add_glyph(self.source_text_stamp, glyph) render_text_stamp = figure.text_stamp(x="xs", y="ys", source=self.source_text_stamp, text=value("🌧"), text_color="colour", text_font_size="fontsize") self.source_text_stamp.js_on_change( 'data', bokeh.models.CustomJS(args=dict( datasource=render_text_stamp.data_source, starting_font_size=starting_font_size, figure=figure, starting_colour=starting_colour), code=""" for(var g = 0; g < datasource.data['fontsize'].length; g++) { if(!datasource.data['colour'][g]) { datasource.data['colour'][g] = starting_colour; } if(!datasource.data['fontsize'][g]) { datasource.data['fontsize'][g] = starting_font_size +'px'; } //calculate initial datasize if(!datasource.data['datasize'][g]) { var starting_font_proportion = starting_font_size/(figure.inner_height); datasource.data['datasize'][g] = (starting_font_proportion * (figure.y_range.end - figure.y_range.start)); } } """)) figure.y_range.js_on_change( 'start', bokeh.models.CustomJS(args=dict( render_text_stamp=render_text_stamp, glyph=render_text_stamp.glyph, figure=figure, starting_font_size=starting_font_size), code=""" for(var g = 0; g < render_text_stamp.data_source.data['fontsize'].length; g++) { render_text_stamp.data_source.data['fontsize'][g] = (((render_text_stamp.data_source.data['datasize'][g])/ (figure.y_range.end - figure.y_range.start))*figure.inner_height) + 'px'; } glyph.change.emit(); """)) #render_text_stamp = bokeh.models.renderers.GlyphRenderer(data_source=ColumnDataSource(dict(x=x, y=y, text="X")), glyph=bokeh.models.Text(x="xs", y="ys", text="text", angle=0.3, text_color="fuchsia")) tool3 = PointDrawTool(renderers=[render_text_stamp], ) return tool3
def result_pic(path_SA, path_S): # mod nmi_value = collections.defaultdict(list) mod_value = collections.defaultdict(list) pic_index = [] for file in os.listdir(path_SA): z = file.find("mod.csv") x = file.find("nmi.csv") if z > -1 or x > -1: if z > -1: print("z") path_mod = path_SA + "/mod.csv" reader = csv.reader(open(path_mod)) for i, line in enumerate(reader): if i != 0: mod_value["SA"].append(line[1]) pic_index.append(str(i)) else: path_nmi = path_SA + "/nmi.csv" reader = csv.reader(open(path_nmi)) for i, line in enumerate(reader): if i != 0: nmi_value["SA"].append(line[1]) # nmi for file in os.listdir(path_S): z = file.find("mod.csv") x = file.find("nmi.csv") if z > -1 or x > -1: if z > -1: path_mod = path_S + "/mod.csv" reader = csv.reader(open(path_mod)) for i, line in enumerate(reader): if i != 0: mod_value["S"].append(line[1]) else: path_nmi = path_S + "/nmi.csv" reader = csv.reader(open(path_nmi)) for i, line in enumerate(reader): if i != 0: nmi_value["S"].append(line[1]) print(mod_value, len(mod_value)) print(nmi_value, len(nmi_value)) df_mod = pd.DataFrame(mod_value, index=pic_index) df_nmi = pd.DataFrame(nmi_value, index=pic_index) col_mod = ColumnDataSource(df_mod) col_nmi = ColumnDataSource(df_nmi) p_mod = figure(x_range=pic_index, y_range=(0, 1), plot_height=350, title="mod", tools="") p_nmi = figure(x_range=pic_index, y_range=(0, 1), plot_height=350, title="nmi", tools="") p_mod.vbar(x=dodge('index', -0.25, range=p_mod.x_range), top='SA', width=0.2, source=col_mod, color="#c9d9d3", legend=value("SA")) p_mod.vbar(x=dodge('index', 0.0, range=p_mod.x_range), top='S', width=0.2, source=col_mod, color="#718dbf", legend=value("S")) p_nmi.vbar(x=dodge('index', -0.25, range=p_nmi.x_range), top='SA', width=0.2, source=col_nmi, color="#c9d9d3", legend=value("SA")) p_nmi.vbar(x=dodge('index', 0.0, range=p_nmi.x_range), top='S', width=0.2, source=col_nmi, color="#718dbf", legend=value("S")) show(p_nmi) show(p_mod)
def _plot_public_data_statistics(self, all_data, version_attr_name, title_name, label_cb): """ generic method to plot flight hours one data type :param all_data: list with all types as string :param version_attr_name: attribute name of _VersionData :param title_name: name of the data for the title (and hover tool) :param label_cb: callback to create the label :return: bokeh plot """ # change data structure data_hours = {} # key=data id, value=list of hours for each version for d in all_data: data_hours[d] = [] versions = [] # sorted list of all versions for ver in sorted(self._version_data, key=functools.cmp_to_key(_Log.compare_version)): versions.append(ver) # all data points of the requested type for this version version_type_data = getattr(self._version_data[ver], version_attr_name) for d in all_data: if not d in version_type_data: version_type_data[d] = 0. data_hours[d].append(version_type_data[d]) # cumulative over each version for key in all_data: data_hours[key] = np.array(data_hours[key]) data_hours[key + "_cum"] = np.cumsum(data_hours[key]) # create a 2D numpy array. We could directly pass the dict to the bokeh # plot, but then we don't have control over the sorting order X = np.zeros((len(all_data), len(versions))) i = 0 all_data_sorted = [] for key in sorted( all_data, key=lambda data_key: data_hours[data_key + "_cum"][-1]): X[i, :] = data_hours[key + "_cum"] all_data_sorted.append(key) i += 1 all_data = all_data_sorted colors = viridis(len(all_data)) # alternative: use patches: http://bokeh.pydata.org/en/latest/docs/gallery/brewer.html area = Area(X, title="Flight Hours per " + title_name, tools=TOOLS, active_scroll=ACTIVE_SCROLL_TOOLS, stack=True, xlabel='version (including development states)', ylabel='', color=colors) # now set the labels for i in range(len(all_data)): area.legend[0].items[i].label = props.value( label_cb(all_data[i], False)) area.legend[0].items.reverse() # stack the data: we'll need it for the hover tool last = np.zeros(len(versions)) for i in range(len(all_data)): last = last + X[i, :] data_hours[all_data[i] + '_stacked'] = last data_hours['x'] = np.arange(len(versions)) # hover tool source = ColumnDataSource(data=data_hours) for d in all_data: renderer = area.circle(x='x', y=d + '_stacked', source=source, size=10, alpha=0, name=d) g1_hover = HoverTool(renderers=[renderer], tooltips=[ (title_name, label_cb(d, True)), ('Flight hours (only this version)', '@' + d + '{0,0.0}'), ('Flight hours (up to this version)', '@' + d + '_cum{0,0.0}') ]) area.add_tools(g1_hover) # TODO: space x-axis entries according to version release date? area.xaxis.formatter = FuncTickFormatter(code=""" var versions = """ + str(versions) + """; return versions[Math.floor(tick)] """) area.xaxis.ticker = FixedTicker(ticks=list(range(len(versions)))) self._setup_plot(area) return area
def bar_chart_continent_split(): # reads df from file df = pd.read_csv('bokeh-server/static/university_ranking.csv', index_col=0) # splits data-frame into top 800 data-frames per year df2016 = df.loc[df['year'] == 2016].head(800) df2017 = df.loc[df['year'] == 2017].head(800) df2018 = df.loc[df['year'] == 2018].head(800) dfs = [df2016, df2017, df2018] # continent order that I wanted continents = ['Europe', 'America', 'Asia', 'Oceania', 'Africa'] list = [] # all years years = ['2016', '2017', '2018'] # all continents put into lists continents_2016 = df2016['continent'].tolist() continents_2017 = df2017['continent'].tolist() continents_2018 = df2018['continent'].tolist() # all continents counter and put into dictionaries count_2016 = dict(Counter(continents_2016)) count_2017 = dict(Counter(continents_2017)) count_2018 = dict(Counter(continents_2018)) # lists of counts in corrrect order as outlined above list2016 = [count_2016[key] for key in continents] list2017 = [count_2017[key] for key in continents] list2018 = [count_2018[key] for key in continents] # dictionary with data for making a figure data = { 'continents': continents, '2016': list2016, '2017': list2017, '2018': list2018 } source = ColumnDataSource(data=data) p = figure(x_range=continents, y_range=(0, 450), plot_height=250, plot_width=700, title="University count per continent per year", tools=['hover', 'save'], tooltips='No. of universities: @$name') p.vbar(x=dodge('continents', -0.25, range=p.x_range), top='2016', width=0.2, source=source, color="#c9d9d3", legend=value("2016"), name='2016') p.vbar(x=dodge('continents', 0.0, range=p.x_range), top='2017', width=0.2, source=source, color="#718dbf", legend=value("2017"), name='2017') p.vbar(x=dodge('continents', 0.25, range=p.x_range), top='2018', width=0.2, source=source, color="#e84d60", legend=value("2018"), name='2018') p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_right" p.legend.orientation = "horizontal" data_frame = pd.DataFrame.from_dict(data) data_frame['mean'] = data_frame.mean(axis=1) data_frame['std'] = data_frame.std(axis=1) data_frame[['mean', 'std']] = data_frame[['mean', 'std']].astype(int) return p, data_frame
else: ty = sy.lambdify(xs, tx, modules=['numpy'])(x) return x, fy, ty source = ColumnDataSource(data=dict(x=[], fy=[], ty=[])) p = figure(x_range=(-7,7), y_range=(-100, 200), plot_width=800, plot_height=400) line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source) line_t = p.line(x="x", y="ty", line_color="firebrick", line_width=2, source=source) p.background_fill_color = "lightgrey" legend = Legend(location="top_right") legend.items = [ LegendItem(label=value("%s" % expr), renderers=[line_f]), LegendItem(label=value("taylor(%s)" % expr), renderers=[line_t]), ] p.add_layout(legend) def update(): try: expr = sy.sympify(text.value, dict(x=xs)) except Exception as exception: errbox.text = str(exception) else: errbox.text = "" x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200) p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.value, expr) legend.items[0].label = value("%s" % expr)
source = ColumnDataSource(data=data) p = figure(x_range=gpa, plot_height=500, plot_width=800, title='GPA count by year', toolbar_location=None, tools="") p.vbar_stack(years, x='gpa', width=0.9, color=colors, source=source, legend=[value(x) for x in years]) p.y_range.start = 0 p.legend.location = "top_center" p.legend.orientation = "vertical" layout_query = layout([ [wb(btnGroupLetters, width=1000)], [wb(btnGroupTitle), wb(btnGroupDept)], [wb(title_input), wb(paragraph, optionGroup, width=100), wb(dept_input)], [wb(refresh, width=100)], [wb(table)], ])
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ["2015", "2016", "2017"] colors = ["#c9d9d3", "#718dbf", "#e84d60"] data = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} source = ColumnDataSource(data=data) p = figure(x_range=fruits, plot_height=350, title="Fruit Counts by Year", toolbar_location=None, tools="") renderers = p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=source, legend=[value(x) for x in years], name=years) for r in renderers: year = r.name hover = HoverTool(tooltips=[ ("%s total" % year, "@%s" % year), ("index", "$index") ], renderers=[r]) p.add_tools(hover) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_left"
def make_axis(axis, size, factors, dim, flip=False, rotation=0, label_size=None, tick_size=None, axis_height=35): factors = list(map(dim.pprint_value, factors)) nchars = np.max([len(f) for f in factors]) ranges = FactorRange(factors=factors) ranges2 = Range1d(start=0, end=1) axis_label = dim_axis_label(dim) reset = "range.setv({start: 0, end: range.factors.length})" ranges.callback = CustomJS(args=dict(range=ranges), code=reset) axis_props = {} if label_size: axis_props['axis_label_text_font_size'] = value(label_size) if tick_size: axis_props['major_label_text_font_size'] = value(tick_size) tick_px = font_size_to_pixels(tick_size) if tick_px is None: tick_px = 8 label_px = font_size_to_pixels(label_size) if label_px is None: label_px = 10 rotation = np.radians(rotation) if axis == 'x': align = 'center' # Adjust height to compensate for label rotation height = int(axis_height + np.abs(np.sin(rotation)) * ((nchars*tick_px)*0.82)) + tick_px + label_px opts = dict(x_axis_type='auto', x_axis_label=axis_label, x_range=ranges, y_range=ranges2, plot_height=height, plot_width=size) else: # Adjust width to compensate for label rotation align = 'left' if flip else 'right' width = int(axis_height + np.abs(np.cos(rotation)) * ((nchars*tick_px)*0.82)) + tick_px + label_px opts = dict(y_axis_label=axis_label, x_range=ranges2, y_range=ranges, plot_width=width, plot_height=size) p = Figure(toolbar_location=None, tools=[], **opts) p.outline_line_alpha = 0 p.grid.grid_line_alpha = 0 if axis == 'x': p.yaxis.visible = False axis = p.xaxis[0] if flip: p.above = p.below p.below = [] p.xaxis[:] = p.above else: p.xaxis.visible = False axis = p.yaxis[0] if flip: p.right = p.left p.left = [] p.yaxis[:] = p.right axis.major_label_orientation = rotation axis.major_label_text_align = align axis.major_label_text_baseline = 'middle' axis.update(**axis_props) return p
def stacked(player): playerStats = generateStatsForPlayer(player) pitch_breakdown = playerStats['stats'] years = [] pitches = ['Fastball', 'Changeup', 'Curve', 'Cutter', 'Splitter', 'Knuckle', 'Slider', 'Sinker', 'Other'] fastballs = [] changeups = [] curves = [] cutters = [] splitters = [] knuckles = [] sliders = [] sinkers = [] others =[] for item in pitch_breakdown: yr = item['year'] years.append(yr) fastballs.append(float(item['percent_fastball'])) changeups.append(float(item['percent_changeup'])) curves.append(float(item['percent_curve'])) cutters.append(float(item['percent_cutter'])) splitters.append(float(item['percent_splitter'])) knuckles.append(float(item['percent_knuckle'])) sliders.append(float(item['percent_slider'])) sinkers.append(float(item['percent_sinker'])) others.append(float(item['percent_other'])) throws = [] data = { 'Year': years } for perc in fastballs: if perc != 0: throws.append('Fastball') data['Fastball'] = fastballs break for perc in changeups: if perc != 0: throws.append('Changeup') data['Changeup'] = changeups break for perc in curves: if perc != 0: throws.append('Curve') data['Curve'] = curves break for perc in cutters: if perc != 0: throws.append('Cutter') data['Cutter'] = cutters break for perc in splitters: if perc != 0: throws.append('Splitter') data['Splitter'] = splitters break for perc in knuckles: if perc != 0: throws.append('Knuckle') data['Knuckle'] = knuckles break for perc in sliders: if perc != 0: throws.append('Slider') data['Slider'] = sliders break for perc in sinkers: if perc != 0: throws.append('Sinker') data['Sinker'] = sinkers break for perc in others: if perc != 0: throws.append('Other') data['Other'] = others break colors = Category20c[len(throws)] # return jsonify(data) p = figure(x_range=years, plot_height=350, plot_width=800, title="Pitch Breakdown By Year", toolbar_location=None, tools="") p.vbar_stack(throws, x='Year', width=0.9, color=colors, source=data, legend=[value(x) for x in throws]) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "center_right" p.legend.orientation = "vertical" new_legend = p.legend[0] p.legend[0].plot = None p.add_layout(new_legend, 'right') script, div = components(p) Flask(__name__).logger.info(script) return [script,div]
from bokeh.core.properties import value from bokeh.io import show, output_file from bokeh.plotting import figure output_file("bar_stacked.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ["2015", "2016", "2017"] colors = ["#c9d9d3", "#718dbf", "#e84d60"] data = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year", toolbar_location=None, tools="hover", tooltips="$name @fruits: @$name") p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data, legend=[value(x) for x in years]) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p)
def vacantPlot(): dfvt = pd.read_csv('BokehApp/Data/HousesVacants.csv', delimiter='\t', header=0) dfvt = dfvt.iloc[:4] dfv = dfvt[['Type', 'Dublin city & suburbs','Rural']] dfv['Other cities'] = dfvt.iloc[:, 2:-2].sum(axis=1) dfv.set_index('Type', inplace=True) dfv.columns = ['Dublin&Suburbs', 'Rural', 'Other cities'] dfv = dfv[['Dublin&Suburbs', 'Other cities', 'Rural']] rowX = dfv.index.values[::] xLabel = ['Dublin', 'Other cities', 'Rural'] lDict = {'For Sale': xLabel, 'Deceased':xLabel, 'Vacant Long Term':xLabel, 'Rental Property':xLabel} source = ColumnDataSource(data=dict(x= list(dfv.index.values), y=dfv['Dublin&Suburbs'], y1=dfv['Other cities'], y2=dfv['Rural'])) p = figure(x_range=FactorRange(*lDict), plot_height=350, plot_width=550, title='Vacant properties in Ireland 2016', x_axis_label=None, y_axis_label=None, tools = 'pan, wheel_zoom, box_zoom, reset') hover = HoverTool() hover.tooltips=[('Vacant properties', 'Dublin @y / Others @y1 / Rural @y2')] p.add_tools(hover) p.vbar(x=dodge('x', -0.25, range=p.x_range), top='y', width=0.2, source=source, color='#FDE724', legend=value('Dublin&Suburbs')) p.vbar(x=dodge('x', 0.0, range=p.x_range), top='y1', width=0.2, source=source, color='#208F8C', legend=value('Other cities')) p.vbar(x=dodge('x', 0.25, range=p.x_range), top='y2', width=0.2, source=source, color='#440154', legend=value('Rural')) tick_labels = {'1000':'1K','2000':'2K','3000':'3K','4000':'4K','5000':'5K'} p.yaxis.major_label_overrides = tick_labels p.legend.location= 'top_right'#(370,180) p.legend.background_fill_alpha=None p.legend.border_line_alpha=0 p.legend.label_text_font_size = "11px" p.y_range.end = dfv.values.max()*1.1+1 p.legend.click_policy="hide" p.title.text_font_size = '15px' p.xaxis.major_label_text_font_style = 'bold' p.grid.grid_line_alpha = 0.6 p.grid.grid_line_dash = 'dotted' p.grid.grid_line_dash_offset = 5 p.grid.grid_line_width = 2 #p.grid.grid_line_color=None p.toolbar.autohide = True p.outline_line_color=None return p
)) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, plot_width=800, plot_height=400) plot.title.text = "Daylight Hours - Warsaw, Poland" plot.toolbar_location = None patch1 = Patch(x="dates", y="times", fill_color="skyblue", fill_alpha=0.8) plot.add_glyph(patch1_source, patch1) patch2 = Patch(x="dates", y="times", fill_color="orange", fill_alpha=0.8) plot.add_glyph(patch2_source, patch2) sunrise_line = Line(x="dates", y="sunrises", line_color="yellow", line_width=2, label=value("sunrise")) sunrise_line_renderer = plot.add_glyph(source, sunrise_line) sunset_line = Line(x="dates", y="sunsets", line_color="red", line_width=2, label=value("sunset")) sunset_line_renderer = plot.add_glyph(source, sunset_line) text = Text(x="dates", y="times", text="texts", text_align="center") plot.add_glyph(text_source, text) xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"])) xaxis = DatetimeAxis(formatter=xformatter) plot.add_layout(xaxis, 'below') yaxis = DatetimeAxis() plot.add_layout(yaxis, 'left')
def bokeh_plot_bar(preds, name=None, allele=None, title='', width=None, height=100, palette='Set1', tools=True, x_range=None): """Plot bars combining one or more prediction results for a set of peptides in a protein/sequence""" from bokeh.models import Range1d, HoverTool, ColumnDataSource from bokeh.plotting import figure from bokeh.transform import dodge from bokeh.core.properties import value height = 180 seqlen = 0 if width == None: width = 700 sizing_mode = 'scale_width' for P in preds: if P.data is None or len(P.data) == 0: continue seqlen = get_seq_from_binders(P) if x_range == None: x_range = Range1d(0, seqlen) y_range = Range1d(start=0, end=1) if tools == True: tools = "xpan, xwheel_zoom, reset, hover" else: tools = None plot = figure(title=title, plot_width=width, sizing_mode=sizing_mode, plot_height=height, y_range=y_range, x_range=x_range, y_axis_label='rank', tools=tools) colors = get_bokeh_colors(palette) data = {} mlist = [] for pred in preds: m = pred.name df = pred.data if df is None or len(df) == 0: continue if name != None: df = df[df.name == name] grps = df.groupby('allele') alleles = grps.groups.keys() if allele not in alleles: continue #print (m, alleles, allele) df = df[df.allele == allele] df = df.sort_values('pos').set_index('pos') key = pred.scorekey X = df[key] X = (X + abs(X.min())) / (X.max() - X.min()) data[m] = X.values data['pos'] = list(X.index) #data['peptide'] = df.peptide.values mlist.append(m) source = ColumnDataSource(data) w = round(1.0 / len(mlist), 1) - .1 i = -w / 2 for m in mlist: #m = pred.name c = colors[m] plot.vbar(x=dodge('pos', i, range=plot.x_range), top=m, width=w, source=source, color=c, legend=value(m), alpha=.8) i += w hover = plot.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ #("allele", "@allele"), ("pos", "@pos") ]) plot.min_border = 10 plot.background_fill_color = "beige" plot.background_fill_alpha = 0.5 plot.toolbar.logo = None plot.toolbar_location = "right" plot.legend.location = "top_right" plot.legend.orientation = "horizontal" return plot
import numpy as np import pandas as pd from bokeh.core.properties import value from bokeh.plotting import figure, show, output_file from bokeh.palettes import brewer output_file('stacked_area.html') N = 10 df = pd.DataFrame(np.random.randint(10, 100, size=(15, N))).add_prefix('y') p = figure(x_range=(0, len(df)-1), y_range=(0, 800)) p.grid.minor_grid_line_color = '#eeeeee' names = ["y%d" % i for i in range(N)] p.varea_stack(stackers=names, x='index', color=brewer['Spectral'][N], legend=[value(x) for x in names], source=df) # reverse the legend entries to match the stacked order p.legend[0].items.reverse() show(p)
] stageTable = DataTable(source=stageSource, columns=stageColumns, height=250) stageHistogram = figure(x_range=cancerStage, y_range=(0, 90), plot_height=400, title="Lung Cancer Stage", toolbar_location=None, tools="") stageHistogram.vbar(x=dodge('Stage', -0.25, range=stageHistogram.x_range), top='Primary', width=0.2, source=stageSource, color="#c9d9d3", legend=value("Primary")) stageHistogram.vbar(x=dodge('Stage', 0.0, range=stageHistogram.x_range), top='Node', width=0.2, source=stageSource, color="#718dbf", legend=value("Node")) stageHistogram.vbar(x=dodge('Stage', 0.25, range=stageHistogram.x_range), top='Mets', width=0.2, source=stageSource, color="#e84d60", legend=value("Mets"))
def disable_minor_ticks(fig): fig.axis.major_label_text_font_size = value('8pt') fig.axis.minor_tick_line_color = None fig.axis.major_tick_in = 0
xformatter = DatetimeTickFormatter(months="%b %d %Y") from time import mktime min_time = dt.datetime.min.time() xticker = FixedTicker(ticks=[ mktime(dt.datetime.combine(summer_start, min_time).timetuple()) * 1000, mktime(dt.datetime.combine(summer_end, min_time).timetuple()) * 1000 ]) xaxis = DatetimeAxis(formatter=xformatter, ticker=xticker) plot.add_layout(xaxis, 'below') yaxis = DatetimeAxis() yaxis.formatter.hours = ['%H:%M'] plot.add_layout(yaxis, 'left') legend = Legend(items=[ LegendItem(label=value('sunset'), renderers=[sunset_line_renderer]), LegendItem(label=value('sunrise'), renderers=[sunrise_line_renderer]), ]) plot.add_layout(legend) doc = Document() doc.add_root(plot) if __name__ == "__main__": doc.validate() filename = "daylight.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Daylight Plot")) print("Wrote %s" % filename) view(filename)
plot_width=1100, x_range=FactorRange(*dfSource.index)) # This creates a hover tool to display data when mousing over bars # The mouse over tool tip will have areas for protected, multiple use, and total tt = HoverTool( tooltips=[("Protected", "@Protected{0,0}"), ( "Multiple Use", "@{Multiple Use}{0,0}"), ("Total", "@{Total Area}{0,0}")]) p.vbar_stack(dfSource.columns[0:2], x='CatCls', width=0.8, color=colors, source=dfSource, legend=[value(x) for x in dfSource.columns[0:2]]) # Add the hover tooltip p.add_tools(tt) p.title.align = "center" p.title.text_font_size = '12pt' p.legend.location = "top_center" p.legend.orientation = "horizontal" p.xaxis.major_label_orientation = 1.55 p.xaxis.axis_label_text_font_style = "normal" p.y_range.start = 0 p.y_range.end = 150000 p.yaxis[0].formatter = NumeralTickFormatter(format="0,0") p.yaxis.axis_label = "Square Kilometers" p.yaxis.axis_label_text_font_style = "normal" show(p)
self.outf.write('%f\t%s\n' % (t,powr)) self.outf.flush() # use a hard disk, not an SD card... print >> sys.stdout,'@',t,'y=',powr self.ds.data['x'].append(tdt) self.ds.data['y'].append(powr) self.ds.trigger('data', self.ds.data, self.ds.data) # create a plot and style its properties p = figure(plot_width=800, plot_height=600, x_axis_type="datetime") p.xaxis.axis_label = "Time" p.xaxis.axis_label_text_color = "darkred" p.axis.major_label_text_font_size=value("10pt") p.xaxis.major_label_orientation = "vertical" p.yaxis.axis_label = "Power (KW)" p.lod_threshold = 1000 # add a text renderer to out plot (no data yet) p.line(x=[], y=[], name="power_line",line_width="2",line_color="blue") renderer = p.select(dict(name="power_line")) ds = renderer[0].data_source m = mq(outfname='mqtt_emon.xls',subs=SUBSCRIPTIONS, server = SERVER_IP,port=1883,timeout=60,looptimeout=1,ds=ds) def callstop():
("Q1", "jan"), ("Q1", "feb"), ("Q1", "mar"), ("Q2", "apr"), ("Q2", "may"), ("Q2", "jun"), ("Q3", "jul"), ("Q3", "aug"), ("Q3", "sep"), ("Q4", "oct"), ("Q4", "nov"), ("Q4", "dec"), ] regions = ['east', 'west'] source = ColumnDataSource(data=dict( x=factors, east=[ 5, 5, 6, 5, 5, 4, 5, 6, 7, 8, 6, 9 ], west=[ 5, 7, 9, 4, 5, 4, 7, 7, 7, 6, 6, 7 ], )) p = figure(x_range=FactorRange(*factors), plot_height=250, toolbar_location=None, tools="") p.vbar_stack(regions, x='x', width=0.9, alpha=0.5, color=["blue", "red"], source=source, legend=[value(x) for x in regions]) p.y_range.start = 0 p.y_range.end = 18 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None p.legend.location = "top_center" p.legend.orientation = "horizontal" show(p)
def nonOccupiers(): #bokeh_doc = curdoc() dfn = pd.read_csv('BokehApp/Data/TT_nonOccupier.csv', delimiter='\t', index_col='Years') dfnt = dfn[['Total Transactions', 'Total Non-Occupiers']] rowX = '2010', '2011','2012','2013','2014','2015','2016', '2017', '2018' sourcent = ColumnDataSource(data=dict( x = rowX, y=dfnt['Total Transactions'], y1=dfnt['Total Non-Occupiers'])) pn = figure(x_range=rowX, plot_height=350, plot_width=550, title='Properties Transactions in Ireland', y_axis_label=None, x_axis_label=None, tools = 'pan, wheel_zoom, box_zoom, reset') pn.vbar(x=dodge('x', 0.0, range=pn.x_range), top='y', width=0.3, source=sourcent, color='#440154', legend=value('Total Transactions')) pn.vbar(x=dodge('x', -0.35, range=pn.x_range), top='y1', width=0.3, source=sourcent, color='#FDE724', legend=value('Total Non-Occupiers')) pn.x_range.range_padding = 0.05 pn.legend.location = 'top_left' hoverpn = HoverTool() hoverpn.tooltips=[('Transactions', 'total @y / non-occupiers @y1')] pn.add_tools(hoverpn) tick_labelspn = {'10000':'10K','20000':'20K','30000':'30K','40000':'40K','50000':'50K', '60000':'60K'} pn.yaxis.major_label_overrides = tick_labelspn pn.legend.background_fill_alpha=None pn.legend.border_line_alpha=0 pn.legend.label_text_font_size = "11px" pn.y_range.end = dfnt.values.max()*1.1+1 pn.legend.click_policy="hide" pn.title.text_font_size = '15px' pn.xaxis.major_label_text_font_style = 'bold' pn.grid.grid_line_color=None pn.toolbar.autohide = True #return pn #show(pn)def NonOccupiers(): dfn1 = pd.read_csv('BokehApp/Data/TT_nonOccupier.csv', delimiter='\t', index_col='Years') dfn3 = dfn1[['Former Owner-Occupier', 'Non-Occupier', 'Non-Household Buyer']] rX = '2010', '2011','2012','2013','2014','2015','2016', '2017', '2018' srcn3 = ColumnDataSource(data=dict( x = rX, y=dfn3['Former Owner-Occupier'], y1=dfn3['Non-Occupier'], y2=dfn3['Non-Household Buyer'])) pn3 = figure(x_range=rX, plot_height=350, plot_width=550, title='Properties Transactions in Ireland', y_axis_label=None, x_axis_label=None, tools = 'pan, wheel_zoom, box_zoom, reset') pn3.line(x='x', y='y', line_width=2.5, line_color='#440154', source=srcn3, legend=value('Former Owner-Occupier')) pn3.line(x='x', y='y1', line_width=2.5, line_color='#FDE724', source=srcn3, legend=value('Non-Occupier')) pn3.circle(x='x', y='y', size=5, color='#B2DD2C', source=srcn3, legend=value('Former Owner-Occupier')) pn3.circle(x='x', y='y1', size=5, color='#440154', source=srcn3, legend=value('Non-Occupier')) pn3.line(x='x', y='y2', line_width=2.5, line_color='#9DD93A', source=srcn3, legend=value('Non-Household Buyer')) pn3.circle(x='x', y='y2', size=5, color='#365A8C', source=srcn3, legend=value('Non-Household Buyer')) #pne.vbar(x='x', top='y', width=0.4, source=srcne, color='#440154', legend=value('Existing')) #pne.vbar(x='x', top='y1', width=0.4, source=srcne, color='#FDE724', legend=value('New')) pn3.legend.location = 'top_left' hoverpn3 = HoverTool() hoverpn3.tooltips=[('Former Owner', '@y'),('Non-Occupier', '@y1'), ('Non-Household', '@y2')] pn3.add_tools(hoverpn3) tick_labelspn3 = {'5000':'5K','10000':'10K','15000':'15K','20000':'20K','25000':'25K'} pn3.yaxis.major_label_overrides = tick_labelspn3 #pn.xaxis.major_label_overrides = {'2010':'2010', '2011':'2011'} #pn3.legend.background_fill_alpha=None #pn3.legend.border_line_alpha=0 pn3.legend.label_text_font_size = "11px" #pne.y_range.end = dfnt.values.max()*1.1+1 #pn.x_range.start = rowX*1.1+1 pn3.legend.click_policy="hide" pn3.title.text_font_size = '15px' pn3.xaxis.major_label_text_font_style = 'bold' #pn3.xgrid.grid_line_color=None pn3.grid.grid_line_alpha = 0.6 pn3.grid.grid_line_dash = 'dotted' pn3.grid.grid_line_dash_offset = 5 pn3.grid.grid_line_width = 2 pn3.toolbar.autohide = True pn3.outline_line_color=None pn3.legend.background_fill_alpha=None pn3.legend.border_line_alpha=0 #return pn3 #show(pn3) dfne = pd.read_csv('BokehApp/Data/HT_NewExisiting.csv', delimiter='\t', index_col='Years') rX = '2010', '2011','2012','2013','2014','2015','2016', '2017', '2018' srcne = ColumnDataSource(data=dict( x = rX, y=dfne['Existing'], y1=dfne['New'])) pne = figure(x_range=rX, plot_height=350, plot_width=550, title='Properties Transactions in Ireland', y_axis_label=None, x_axis_label=None, tools = 'pan, wheel_zoom, box_zoom, reset') pne.line(x='x', y='y', line_width=2.5, line_color='#440154', source=srcne, legend=value('Existing')) pne.line(x='x', y='y1', line_width=2.5, line_color='#FDE724', source=srcne, legend=value('New')) pne.circle(x='x', y='y', size=5, color='#B2DD2C', source=srcne, legend=value('Existing')) pne.circle(x='x', y='y1', size=5, color='#35B778', source=srcne, legend=value('New')) #pne.vbar(x='x', top='y', width=0.4, source=srcne, color='#440154', legend=value('Existing')) #pne.vbar(x='x', top='y1', width=0.4, source=srcne, color='#FDE724', legend=value('New')) pne.legend.location = 'top_left' hoverpne = HoverTool() hoverpne.tooltips=[('Transactions', 'Exisiting @y / New @y1')] pne.add_tools(hoverpne) tick_labelspne = {'10000':'10K','20000':'20K','30000':'30K','40000':'40K'} pne.yaxis.major_label_overrides = tick_labelspne #pn.xaxis.major_label_overrides = {'2010':'2010', '2011':'2011'} pne.legend.background_fill_alpha=None pne.legend.border_line_alpha=0 pne.legend.label_text_font_size = "11px" #pne.y_range.end = dfnt.values.max()*1.1+1 #pn.x_range.start = rowX*1.1+1 pne.legend.click_policy="hide" pne.title.text_font_size = '15px' pne.xaxis.major_label_text_font_style = 'bold' #pne.xgrid.grid_line_color=None pne.grid.grid_line_alpha = 0.6 pne.grid.grid_line_dash = 'dotted' pne.grid.grid_line_dash_offset = 5 pne.grid.grid_line_width = 2 pne.toolbar.autohide = True pne.outline_line_color=None #show(pne) dfn = pd.read_csv('BokehApp/Data/TT_nonOccupier.csv', delimiter='\t', index_col='Years') dfnt = dfn[['Total Transactions', 'Total Non-Occupiers']] rowX = '2010', '2011','2012','2013','2014','2015','2016', '2017', '2018' sourcent = ColumnDataSource(data=dict( x = rowX, y=dfnt['Total Transactions'], y1=dfnt['Total Non-Occupiers'])) pn = figure(x_range=rowX, plot_height=350, plot_width=550, title='Properties Transactions in Ireland', y_axis_label=None, x_axis_label=None, tools = 'pan, wheel_zoom, box_zoom, reset') #pn.x_range=rowX pn.vbar(x=dodge('x', 0.0, range=pn.x_range), top='y', width=0.3, source=sourcent, color='#440154', legend=value('Total Transactions')) pn.vbar(x=dodge('x', -0.35, range=pn.x_range), top='y1', width=0.3, source=sourcent, color='#FDE724', legend=value('Total Non-Occupiers')) #pn.x_range.factors = xstr #x_range = FactorRange(factors=['2010', '2011', '2012','2013','2014','2015','2016','2017','2018']) pn.x_range.range_padding = 0.05 pn.legend.location = 'top_left' hoverpn = HoverTool() hoverpn.tooltips=[('Transactions', 'total @y / non-occupiers @y1')] pn.add_tools(hoverpn) tick_labelspn = {'10000':'10K','20000':'20K','30000':'30K','40000':'40K','50000':'50K', '60000':'60K'} pn.yaxis.major_label_overrides = tick_labelspn #pn.xaxis.major_label_overrides = {'2010':'2010', '2011':'2011'} pn.legend.background_fill_alpha=None pn.legend.border_line_alpha=0 pn.legend.label_text_font_size = "11px" pn.y_range.end = dfnt.values.max()*1.1+1 #pn.x_range.start = rowX*1.1+1 pn.legend.click_policy="hide" pn.title.text_font_size = '15px' pn.xaxis.major_label_text_font_style = 'bold' #pn.grid.grid_line_color=None pn.grid.grid_line_alpha = 0.6 pn.grid.grid_line_dash = 'dotted' pn.grid.grid_line_dash_offset = 5 pn.grid.grid_line_width = 2 pn.toolbar.autohide = True pn.outline_line_color=None #show(pn) t1 = Panel(child=pn, title='Overview') t2 = Panel(child=pne, title='Type of sale') t3 = Panel(child=pn3, title='Type of buyer') tabs = Tabs(tabs=[t1,t2,t3]) return tabs