def make_plot(source, xname, yname, line_color, xdr=None, ydr=None, min_border=15, x_axis=True, y_axis=True, responsive=MODE, plot_width=600, plot_height=400): """ Returns a tuple (plot, [obj1...objN]); the former can be added to a GridPlot, and the latter is added to the plotcontext. """ if not xdr: xdr = DataRange1d() if not ydr: ydr = DataRange1d() #title = Title(text='hello world', render_mode='canvas') plot = Plot( x_range=xdr, y_range=ydr, min_border=min_border, toolbar_location=None, responsive=responsive, plot_width=plot_width, plot_height=plot_height, title="Plot title", ) if x_axis: plot.add_layout(LinearAxis(), 'below') if y_axis: plot.add_layout(LinearAxis(), 'left') plot.add_glyph(source, Line(x=xname, y=yname, line_color=line_color)) return plot
def construct_line(source, value_string, line_color=BLUE): xdr = Range1d(1990, 2013) ydr = Range1d(0, 100) line_plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=250, plot_height=150, min_border_top=10, min_border_left=50, **PLOT_FORMATS ) xaxis = LinearAxis(SingleIntervalTicker(interval=50), **AXIS_FORMATS) yaxis = LinearAxis(SingleIntervalTicker(interval=10), **AXIS_FORMATS) line_plot.add_layout(xaxis, 'left') line_plot.add_layout(yaxis, 'below') line = Line( x='year', y=value_string, line_width=5, line_cap="round", line_color=line_color, ) line_plot.add_glyph(source, line) return line_plot
def test_patches_hover_still_works_when_a_seleciton_is_preselcted(output_file_url, selenium): # This tests an edge case interaction when Patches (specifically) is used # with a tool that requires hit testing e.g. HitTool AND a selection is # pre-made on the data source driving it. plot = Plot( x_range=Range1d(0, 100), y_range=Range1d(0, 100), min_border=0 ) source = ColumnDataSource(dict( xs=[[0, 50, 50, 0], [50, 100, 100, 50]], ys=[[0, 0, 100, 100], [0, 0, 100, 100]], color=['pink', 'blue'] )) source.selected = { '0d': {'glyph': None, 'indices': []}, '1d': {'indices': [1]}, '2d': {} } plot.add_glyph(source, Patches(xs='xs', ys='ys', fill_color='color')) plot.add_tools(HoverTool()) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') save(plot) selenium.get(output_file_url) assert has_no_console_errors(selenium) # Hover plot and test no error canvas = selenium.find_element_by_tag_name('canvas') actions = ActionChains(selenium) actions.move_to_element_with_offset(canvas, 100, 100) actions.perform() # If this assertion fails then there were likely errors on hover assert has_no_console_errors(selenium)
def get_ws_plot( data, plot_height=300, plot_width=800, column_names=cs.column_names_weewx, column_time=cs.time_column_name_weewx, border_left=200, ): data_seconds = data data_seconds.iloc[:, 0] = data_seconds.iloc[:, 0] * 1000 plot = Plot( x_range=DataRange1d(), y_range=DataRange1d(), plot_width=plot_width, plot_height=plot_height, min_border_left=border_left, **kwargs ) add_glyphs_to_plot(column_names, column_time, data_seconds, plot) plot.add_layout(DatetimeAxis(), "below") plot.add_tools(PanTool(), WheelZoomTool(), ResizeTool(), CrosshairTool()) return plot
def altitude_profile(data): plot = Plot(title="%s - Altitude Profile" % title, plot_width=800, plot_height=400) plot.x_range = DataRange1d() plot.y_range = DataRange1d() xaxis = LinearAxis(axis_label="Distance (km)") plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="Altitude (m)") plot.add_layout(yaxis, 'left') xgrid = Grid(plot=plot, dimension=0, ticker=xaxis.ticker) ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker) plot.renderers.extend([xgrid, ygrid]) plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) X, Y = data.dist, data.alt y0 = min(Y) patches_source = ColumnDataSource(dict( xs=[[X[i], X[i+1], X[i+1], X[i]] for i in range(len(X[:-1])) ], ys=[[y0, y0, Y[i+1], Y[i]] for i in range(len(Y[:-1])) ], color=data.colors[:-1] )) patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color") plot.add_glyph(patches_source, patches) line_source = ColumnDataSource(dict(x=data.dist, y=data.alt)) line = Line(x='x', y='y', line_color="black", line_width=1) plot.add_glyph(line_source, line) return plot
def __init__(self, **kwargs): names = ['processes', 'disk-read', 'cores', 'cpu', 'disk-write', 'memory', 'last-seen', 'memory_percent', 'host'] self.source = ColumnDataSource({k: [] for k in names}) columns = {name: TableColumn(field=name, title=name.replace('_percent', ' %')) for name in names} cnames = ['host', 'cores', 'processes', 'memory', 'cpu', 'memory_percent'] formatters = {'cpu': NumberFormatter(format='0.0 %'), 'memory_percent': NumberFormatter(format='0.0 %'), 'memory': NumberFormatter(format='0 b'), 'latency': NumberFormatter(format='0.00000'), 'last-seen': NumberFormatter(format='0.000'), 'disk-read': NumberFormatter(format='0 b'), 'disk-write': NumberFormatter(format='0 b'), 'net-send': NumberFormatter(format='0 b'), 'net-recv': NumberFormatter(format='0 b')} table = DataTable( source=self.source, columns=[columns[n] for n in cnames], ) for name in cnames: if name in formatters: table.columns[cnames.index(name)].formatter = formatters[name] mem_plot = Plot( title=Title(text="Memory Usage (%)"), toolbar_location=None, x_range=Range1d(start=0, end=1), y_range=Range1d(start=-0.1, end=0.1), **kwargs ) mem_plot.add_glyph( self.source, Circle(x='memory_percent', y=0, size=10, fill_alpha=0.5) ) mem_plot.add_layout(LinearAxis(), 'below') hover = HoverTool( point_policy="follow_mouse", tooltips=""" <div> <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span> <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span> </div> """ ) mem_plot.add_tools(hover, BoxSelectTool()) if 'sizing_mode' in kwargs: sizing_mode = {'sizing_mode': kwargs['sizing_mode']} else: sizing_mode = {} self.root = column(mem_plot, table, id='bk-worker-table', **sizing_mode)
def make_figure(axes): xdr = Range1d(start=-1, end=1) ydr = Range1d(start=-1, end=1) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=200, plot_height=200, toolbar_location=None) plot.add_glyph(Circle(x=0, y=0, size=100)) for place in axes: plot.add_layout(LinearAxis(), aliases[place]) return plot
def make_plot(sizing_mode): plot = Plot( x_range=DataRange1d(), y_range=DataRange1d(), toolbar_location=None, sizing_mode=sizing_mode ) plot.add_glyph(source, Line(x="x", y="y1")) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') return plot
def test_color_bar_with_scale_alpha(): plot = Plot(width=WIDTH, height=HEIGHT, x_range=Range1d(0,10), y_range=Range1d(0,10), outline_line_alpha=0.0, toolbar_location=None) bar_vertical_in_frame = create_vertical_color_bar_with_log_cmap() bar_vertical_in_frame.scale_alpha = 0.5 plot.add_layout(bar_vertical_in_frame) return plot
def make_plot(location, title_align, two_axes=True): plot = Plot( plot_width=400, plot_height=200, x_range=Range1d(0, 2), y_range=Range1d(0, 2), toolbar_location=None, title="Title %s - %s" % (location, title_align), title_location=location, ) plot.title.title_align = title_align plot.title.title_padding = 10 plot.add_glyph(source, Circle(x='x', y='y', radius=0.4)) plot.add_layout(LinearAxis(), location) if two_axes: plot.add_layout(LinearAxis(), location) return plot
class MemoryUsage(DashboardComponent): """ The memory usage across the cluster, grouped by task type """ def __init__(self, **kwargs): self.source = ColumnDataSource(data=dict( name=[], left=[], right=[], center=[], color=[], percent=[], MB=[], text=[]) ) self.root = Plot( id='bk-nbytes-plot', x_range=DataRange1d(), y_range=DataRange1d(), toolbar_location=None, outline_line_color=None, **kwargs ) self.root.add_glyph( self.source, Quad(top=1, bottom=0, left='left', right='right', fill_color='color', fill_alpha=1) ) self.root.add_layout(LinearAxis(), 'left') self.root.add_layout(LinearAxis(), 'below') hover = HoverTool( point_policy="follow_mouse", tooltips=""" <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Percent:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@percent</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">MB:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@MB</span> </div> """ ) self.root.add_tools(hover) def update(self, messages): with log_errors(): msg = messages['progress'] if not msg: return nb = nbytes_bar(msg['nbytes']) self.source.data.update(nb) self.root.title.text = \ "Memory Use: %0.2f MB" % (sum(msg['nbytes'].values()) / 1e6)
def make_plot(xname, yname, xax=False, yax=False): mbl = 40 if yax else 0 mbb = 40 if xax else 0 plot = Plot( x_range=xdr, y_range=ydr, background_fill_color="#efe8e2", border_fill_color='white', title="", h_symmetry=False, v_symmetry=False, plot_width=200 + mbl, plot_height=200 + mbb, min_border_left=2+mbl, min_border_right=2, min_border_top=2, min_border_bottom=2+mbb) circle = Circle(x=xname, y=yname, fill_color="color", fill_alpha=0.2, size=4, line_color="color") r = plot.add_glyph(source, circle) xdr.renderers.append(r) ydr.renderers.append(r) xticker = BasicTicker() if xax: xaxis = LinearAxis() plot.add_layout(xaxis, 'below') xticker = xaxis.ticker plot.add_layout(Grid(dimension=0, ticker=xticker)) yticker = BasicTicker() if yax: yaxis = LinearAxis() plot.add_layout(yaxis, 'left') yticker = yaxis.ticker plot.add_layout(Grid(dimension=1, ticker=yticker)) plot.add_tools(PanTool(), WheelZoomTool()) return plot
def make_plot(yname, line_color, below_axis=True, left_axis=True, right_axis=False, border_fill_color="white"): """ Returns a tuple (plot, [obj1...objN]); the former can be added to a GridPlot, and the latter is added to the plotcontext. """ plot = Plot( x_range=DataRange1d(), y_range=DataRange1d(), min_border=15, border_fill_color=border_fill_color, border_fill_alpha=0.1, toolbar_location='above', plot_width=300, plot_height=300, responsive='box' ) if below_axis: plot.add_layout(LinearAxis(), 'below') else: plot.add_layout(LinearAxis(), 'above') if left_axis: plot.add_layout(LinearAxis(), 'left') if right_axis: plot.add_layout(LinearAxis(), 'right') plot.add_glyph(source, Line(x="x", y=yname, line_color=line_color)) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) return plot
def topicplot(): xdr = DataRange1d(sources=[topicsource.columns("width")]) ydr = FactorRange(factors=list(reversed(list(barDefault2.Term)))) #"Top-{R} Most Relevant Terms for Topic {topic} ({count}% of tokens)".format(R=R, ...) title = "Top-{R} Most Salient Terms".format(R=R) plot = Plot(title=title, title_text_font_size="16px", x_range=xdr, y_range=ydr, plot_width=mdswidth, plot_height=mdsheight) plot.add_glyph(topicsource, Rect(x="x", y="y", width="width", height=1, fill_color=base_color, fill_alpha=0.2, line_color=base_color)) plot.add_layout(LinearAxis(), "above") plot.add_layout(CategoricalAxis(), "left") return plot
def pyramid(): xdr = DataRange1d() ydr = DataRange1d() plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=600, plot_height=600) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=5)) plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) male_quad = Quad(left="male", right=0, bottom="groups", top="shifted", fill_color="#3B8686") male_quad_glyph = plot.add_glyph(source_pyramid, male_quad) female_quad = Quad(left=0, right="female", bottom="groups", top="shifted", fill_color="#CFF09E") female_quad_glyph = plot.add_glyph(source_pyramid, female_quad) plot.add_layout(Legend(items=[ ("Male" , [male_quad_glyph]), ("Female" , [female_quad_glyph]), ])) return plot
def test_no_border_or_background_fill(output_file_url, selenium, screenshot): # Have body background-color that should appear through the no-fill plot template = Template(""" <!doctype html> <html lang="en"> <head> {{ bokeh_js }} {{ bokeh_css}} <style> body { background-color: lightblue; } </style> </head> <body> {{ plot_script }} {{ plot_div }} </body> </html> """) plot = Plot(plot_height=HEIGHT, plot_width=WIDTH, x_range=Range1d(0, 10), y_range=Range1d(0, 10), toolbar_location=None) # This is the no-fill that we're testing plot.background_fill_color = None plot.border_fill_color = None plot.add_glyph(Circle(x=3, y=3, size=50, fill_color='#ffffff')) plot.add_glyph(Circle(x=6, y=6, size=50, fill_color='#ffffff')) plot.add_layout(LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="30pt"), 'left') plot.add_layout(LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="30pt"), 'below') html = file_html(plot, INLINE, template=template) # filename has to match test function + '.html' light filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_no_border_or_background_fill.html") with io.open(filepath, "w", encoding="utf-8") as f: f.write(decode_utf8(html)) selenium.get(output_file_url) assert has_no_console_errors(selenium) screenshot.assert_is_valid()
def test_color_bar_placement_and_render(output_file_url, selenium, screenshot): plot = Plot(height=HEIGHT, width=WIDTH, x_range=Range1d(0,10), y_range=Range1d(0,10), toolbar_location=None) bar_vertical_right_panel = create_vertical_color_bar_with_log_cmap() bar_vertical_right_panel.location = (0, 0) bar_vertical_in_frame = create_vertical_color_bar_with_log_cmap() bar_vertical_in_frame.location = "top_right" bar_vertical_in_frame.title = "Dummy Title" bar_vertical_in_frame.title_standoff = 7 bar_horizontal_below_panel = create_horizontal_color_bar_with_linear_cmap() bar_horizontal_below_panel.location = (0, 0) bar_horizontal_in_frame = create_horizontal_color_bar_with_linear_cmap() bar_horizontal_in_frame.location = "bottom_left" bar_horizontal_in_frame.title = "Dummy Title" plot.add_layout(bar_vertical_right_panel, 'right') plot.add_layout(bar_vertical_in_frame) plot.add_layout(bar_horizontal_below_panel, 'below') plot.add_layout(bar_horizontal_in_frame) # Save the plot and start the test save(plot) selenium.get(output_file_url) assert has_no_console_errors(selenium) # Take screenshot screenshot.assert_is_valid()
def test_color_bar_placement_and_render(): plot = Plot(width=WIDTH, height=HEIGHT, x_range=Range1d(0,10), y_range=Range1d(0,10), toolbar_location=None) bar_vertical_right_panel = create_vertical_color_bar_with_log_cmap() bar_vertical_right_panel.location = (0, 0) bar_vertical_in_frame = create_vertical_color_bar_with_log_cmap() bar_vertical_in_frame.location = "top_right" bar_vertical_in_frame.title = "Dummy Title" bar_vertical_in_frame.title_standoff = 7 bar_horizontal_below_panel = create_horizontal_color_bar_with_linear_cmap() bar_horizontal_below_panel.location = (0, 0) bar_horizontal_in_frame = create_horizontal_color_bar_with_linear_cmap() bar_horizontal_in_frame.location = "bottom_left" bar_horizontal_in_frame.title = "Dummy Title" plot.add_layout(bar_vertical_right_panel, 'right') plot.add_layout(bar_vertical_in_frame) plot.add_layout(bar_horizontal_below_panel, 'below') plot.add_layout(bar_horizontal_in_frame) return plot
def get_weather_plot(time_int=None,t_min=None,t_max=None): plot_height = cs.plot_height plot_width = cs.plot_width border_left = cs.border_left column_names = cs.column_names_weewx column_time = cs.time_column_name_weewx if t_max == None or t_min == None: t_max, t_min = get_first_time_interval() t_span = t_max - t_min if time_int == None: time_int = cs.time_int data_seconds = sql_con.get_data_ws(time_int=time_int, t_min=t_min, t_max=t_max) data_seconds.iloc[:, 0] = data_seconds.iloc[:, 0] * 1000 plot = Plot(x_range=DataRange1d(start=(t_min-t_span*.1)*1000, end=(t_max+t_span*.1)*1000), y_range=DataRange1d(), plot_width=plot_width, plot_height=plot_height, # x_axis_type="datetime", min_border_left=border_left, toolbar_location="right") add_glyphs_to_plot(column_names, column_time, data_seconds, plot,'source_weather') plot.add_layout(DatetimeAxis(name="date_time_axis"), 'below') plot.add_tools(PanTool(), WheelZoomTool(), # ResizeTool(), CrosshairTool(), PreviewSaveTool() ) Grid(plot=plot,dimension=0,ticker=plot.select('date_time_axis')[0].ticker) Grid(plot=plot, dimension=1, ticker=plot.select(type=LinearAxis,name=column_names[0])[0].ticker ) set_legends(plot) plot.title = cs.plot_title_weewx + ' averaged to {} seconds'.format(time_int) return plot
def test_color_bar_with_scale_alpha(output_file_url, selenium, screenshot): plot = Plot(height=HEIGHT, width=WIDTH, x_range=Range1d(0,10), y_range=Range1d(0,10), outline_line_alpha=0.0, toolbar_location=None) bar_vertical_in_frame = create_vertical_color_bar_with_log_cmap() bar_vertical_in_frame.scale_alpha = 0.5 plot.add_layout(bar_vertical_in_frame) # Save the plot and start the test save(plot) selenium.get(output_file_url) assert has_no_console_errors(selenium) # Take screenshot screenshot.assert_is_valid()
def make_plot(source, xname, yname, line_color, xdr=None, ydr=None): """ Returns a tuple (plot, [obj1...objN]); the former can be added to a GridPlot, and the latter is added to the plotcontext. """ if xdr is None: xdr = DataRange1d() if ydr is None: ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, min_border=50) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') plot.add_glyph(source, Line(x=xname, y=yname, line_color=line_color)) plot.add_tools(PanTool(), WheelZoomTool()) return plot
def test_rect_rendering_with_log_axis(output_file_url, selenium, screenshot): plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0,30), y_range=Range1d(1,100), y_axis_type="log") x = [10, 20] y = [10, 20] source = ColumnDataSource(data=dict(x=[(x[0]+x[1])/2], y=[(y[0]+y[1])/2], width=[x[1]-x[0]], height=[y[1]-y[0]])) plot.add_glyph(source, Rect(x='x', y='y', width='width', height='height')) plot.add_layout(LogAxis(), "left") # Save the plot and start the test save(plot) selenium.get(output_file_url) assert has_no_console_errors(selenium) screenshot.assert_is_valid()
def make_plot(xr=None, yr=None): if xr is None: x_range = Range1d(0, 3, bounds=None) else: x_range = xr if yr is None: y_range = Range1d(0, 3, bounds=None) else: y_range = yr source = ColumnDataSource(dict(x=[1, 2], y=[1, 1])) # explicitly set plot.id so that the plot can be accessed from Bokeh.index in browser plot = Plot(id='plot-id', plot_height=400, plot_width=400, x_range=x_range, y_range=y_range, min_border=0) plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9)) plot.add_tools(PanTool(), BoxZoomTool()) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') return plot
def population(): xdr = FactorRange(factors=years) ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, plot_width=600, plot_height=150, toolbar_location=None) plot.add_layout(CategoricalAxis(major_label_orientation=pi / 4), 'below') known = Line(x="x", y="y", line_color="violet", line_width=2) known_glyph = plot.add_glyph(source_known, known) predicted = Line(x="x", y="y", line_color="violet", line_width=2, line_dash="dashed") predicted_glyph = plot.add_glyph(source_predicted, predicted) legend = Legend(location="bottom_right", items=[("known", [known_glyph]), ("predicted", [predicted_glyph])]) plot.add_layout(legend) return plot
def make_plot(xname, yname, xax=False, yax=False, text=None): plot = Plot( x_range=xdr, y_range=ydr, background_fill="#efe8e2", border_fill="white", title="", min_border=2, h_symmetry=False, v_symmetry=False, plot_width=250, plot_height=250, ) circle = Circle(x=xname, y=yname, fill_color="color", fill_alpha=0.2, size=4, line_color="color") r = plot.add_glyph(source, circle) xdr.renderers.append(r) ydr.renderers.append(r) xticker = BasicTicker() if xax: xaxis = LinearAxis() plot.add_layout(xaxis, "below") xticker = xaxis.ticker plot.add_layout(Grid(dimension=0, ticker=xticker)) yticker = BasicTicker() if yax: yaxis = LinearAxis() plot.add_layout(yaxis, "left") yticker = yaxis.ticker plot.add_layout(Grid(dimension=1, ticker=yticker)) plot.add_tools(PanTool(), WheelZoomTool()) if text: text = " ".join(text.split("_")) text = Text( x={"field": "xcenter", "units": "screen"}, y={"field": "ycenter", "units": "screen"}, text=[text], angle=pi / 4, text_font_style="bold", text_baseline="top", text_color="#ffaaaa", text_alpha=0.7, text_align="center", text_font_size="28pt", ) plot.add_glyph(text_source, text) return plot
def test_label(output_file_url, selenium, screenshot): # Have to specify x/y range as labels aren't included in the plot area solver plot = Plot(plot_height=HEIGHT, plot_width=WIDTH, x_range=Range1d(0, 10), y_range=Range1d(0, 10), toolbar_location=None) label1 = Label(x=1, y=6, x_offset=25, y_offset=25, text=["Demo Label"], text_font_size='38pt', text_color='red', text_alpha=0.9, text_baseline='bottom', text_align='left', background_fill_color='green', background_fill_alpha=0.2, angle=15, angle_units='deg', render_mode='canvas') label2 = Label(x=3, y=5.5, text=["(I'm Canvas)"], text_font_size='20pt', border_line_color='black', border_line_width=2, border_line_dash='8 4', render_mode='canvas') label3 = Label(x=1, y=2, x_offset=25, y_offset=25, text=["Demo Label"], text_font_size='38pt', text_color='red', text_alpha=0.9, text_baseline='bottom', text_align='left', background_fill_color='green', background_fill_alpha=0.2, angle=0.261, angle_units='rad', render_mode='css') label4 = Label(x=3, y=1.0, text=["(I'm CSS)"], text_font_size='20pt', border_line_color='black', border_line_width=2, border_line_dash='8 4', render_mode='css') plot.renderers.extend([label1, label2, label3, label4]) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') # Save the plot and start the test save(plot) selenium.get(output_file_url) # Take screenshot assert screenshot.is_valid()
def large_plot(n): from bokeh.models import ( Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, SaveTool, ResetTool ) from bokeh.models.layouts import Column from bokeh.models.glyphs import Line col = Column() objects = set([col]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis() plot.add_layout(xaxis, "below") yaxis = LinearAxis() plot.add_layout(yaxis, "left") xgrid = Grid(dimension=0) plot.add_layout(xgrid, "center") ygrid = Grid(dimension=1) plot.add_layout(ygrid, "center") tickers = [xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter] glyph = Line(x='x', y='y') renderer = GlyphRenderer(data_source=source, glyph=glyph) plot.renderers.append(renderer) pan = PanTool() zoom_in = ZoomInTool() zoom_out = ZoomOutTool() wheel_zoom = WheelZoomTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() save = SaveTool() reset = ResetTool() tools = [pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset] plot.add_tools(*tools) col.children.append(plot) objects |= set([ xdr, ydr, xaxis, yaxis, xgrid, ygrid, renderer, renderer.view, glyph, source, source.selected, source.selection_policy, plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title, box_zoom.overlay, box_select.overlay, ] + tickers + tools) return col, objects
def make_plot(title, xname, yname): plot = Plot( x_range=xdr, y_range=ydr, title=title, plot_width=400, plot_height=400, border_fill='white', background_fill='#e9e0db' ) xaxis = LinearAxis(axis_line_color=None) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_line_color=None) plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) line = Line(x='x', y='y', line_color="#666699", line_width=2) plot.add_glyph(lines_source, line) circle = Circle( x=xname, y=yname, size=12, fill_color="#cc6633", line_color="#cc6633", fill_alpha=0.5 ) plot.add_glyph(circles_source, circle) return plot
def make_plot(): xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, plot_width=400, plot_height=400) plot.title.text = "Product downloads" line = Line(x="dates", y="downloads", line_color="blue") plot.add_glyph(source, line) circle = Circle(x="dates", y="downloads", fill_color="red") plot.add_glyph(source, circle) xaxis = DatetimeAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) plot.add_tools(HoverTool(tooltips=dict(downloads="@downloads"))) return plot, source
def population(): xdr = FactorRange(factors=years) ydr = DataRange1d() plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=200) plot.add_layout(CategoricalAxis(major_label_orientation=pi/4), 'below') line_known = Line(x="x", y="y", line_color="violet", line_width=2) line_known_glyph = plot.add_glyph(source_known, line_known) line_predicted = Line(x="x", y="y", line_color="violet", line_width=2, line_dash="dashed") line_predicted_glyph = plot.add_glyph(source_predicted, line_predicted) plot.add_layout( Legend( location="bottom_right", legends=[("known", [line_known_glyph]), ("predicted", [line_predicted_glyph])], ) ) return plot
def plotprotein(sequence, other_binding, dna_binding, metal_binding, active, variant_location): sequence = [i for i in sequence] print(len(sequence)) sequence += [''] * (3000 - len(sequence)) print(sequence) print(variant_location) if variant_location > 50: start_seq = variant_location - 50 else: start_seq = 0 if variant_location + 50 < len(sequence): end_seq = variant_location + 50 else: end_seq = 3000 x_values = range(0, 3000) #x_values = range(starting_value, value) source1 = ColumnDataSource( dict(x=x_values[start_seq:end_seq], y=other_binding[start_seq:end_seq], names=sequence[start_seq:end_seq])) source2 = ColumnDataSource( dict(x=x_values[start_seq:end_seq], y=dna_binding[start_seq:end_seq], names=sequence[start_seq:end_seq])) source3 = ColumnDataSource( dict(x=x_values[start_seq:end_seq], y=metal_binding[start_seq:end_seq], names=sequence[start_seq:end_seq])) source4 = ColumnDataSource( dict(x=x_values[start_seq:end_seq], y=active[start_seq:end_seq], names=sequence[start_seq:end_seq])) glyph1 = Line(x="x", y="y", line_color="red", line_width=3, line_alpha=0.6) glyph2 = Line(x="x", y="y", line_color="blue", line_width=3, line_alpha=0.6) glyph3 = Line(x="x", y="y", line_color="green", line_width=3, line_alpha=0.6) glyph4 = Line(x="x", y="y", line_color="orange", line_width=3, line_alpha=0.6) plot = Plot(title=None, plot_height=150, plot_width=1000, min_border=0, toolbar_location=None) plot.add_glyph(source1, glyph1) plot.add_glyph(source2, glyph2) plot.add_glyph(source3, glyph3) plot.add_glyph(source4, glyph4) plot.add_layout( Span(location=variant_location, dimension='height', line_color='black')) xaxis = LinearAxis() #YOUR_FONT_SIZE = 10 labels = LabelSet(x='x', y=1, text='names', level='glyph', x_offset=-1, y_offset=5, source=source1, render_mode='canvas', text_font_size='5pt') plot.add_layout(labels) yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.yaxis.bounds = (0, 1) plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) plot.y_range = Range1d(-0.1, 1.5) show(plot)
def make_correlation_datatable(correl_df): """ the input datframe must have columns ['Target (as string)', 'Hedge (as string)', 'Correlation ( as float )'] :param correl_df: :return: """ correl_df.reset_index(inplace=True) source = ColumnDataSource(correl_df) target_ts_asset = sorted(correl_df["Target"].unique()) hedge_ts_asset = sorted(correl_df["Hedge"].unique()) columns = [ TableColumn(field="Target", title="Target Timeseries", formatter=StringFormatter(font_style="bold", text_color='red')), TableColumn(field="Hedge", title="Hedge Timeseries", formatter=StringFormatter(font_style="bold", text_color='blue')), TableColumn(field="Correlation", title="Correlation", formatter=StringFormatter(font_style="bold", text_color='darkgreen')) ] data_table = DataTable(source=source, columns=columns, editable=False, width=1000) plot = Plot(title=Title( text="Correlations, Target vs. Hedge Timeseries)", align="center"), x_range=DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs correlation_glyph = Circle(x="index", y="Correlation", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) target_glyph = Circle(x="index", y="Target", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hedge_glyph = Circle(x="index", y="Hedge", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) correlation = plot.add_glyph(source, correlation_glyph) target = plot.add_glyph(source, target_glyph) hedge = plot.add_glyph(source, hedge_glyph) # Add the tools tooltips = [("Correlation", "@Correlation"), ("Target", "@Target"), ("Hedge", "@Hedge")] correlation_hover_tool = HoverTool(renderers=[correlation], tooltips=tooltips) target_hover_tool = HoverTool(renderers=[target], tooltips=tooltips) hedge_hover_tool = HoverTool(renderers=[hedge], tooltips=tooltips) select_tool = BoxSelectTool(renderers=[target, hedge, correlation], dimensions='width') plot.add_tools(target_hover_tool, hedge_hover_tool, correlation_hover_tool, select_tool) layout = Column(plot, data_table) the_doc = Document() the_doc.add_root(layout) return the_doc
def large_plot(n: int) -> Tuple[Model, Set[Model]]: from bokeh.models import ( BoxSelectTool, BoxZoomTool, Column, ColumnDataSource, DataRange1d, GlyphRenderer, Grid, Line, LinearAxis, PanTool, Plot, ResetTool, SaveTool, WheelZoomTool, ZoomInTool, ZoomOutTool, ) col = Column() objects: Set[Model] = {col} for i in range(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis() plot.add_layout(xaxis, "below") yaxis = LinearAxis() plot.add_layout(yaxis, "left") xgrid = Grid(dimension=0) plot.add_layout(xgrid, "center") ygrid = Grid(dimension=1) plot.add_layout(ygrid, "center") tickers = [ xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter ] glyph = Line(x='x', y='y') renderer = GlyphRenderer(data_source=source, glyph=glyph) plot.renderers.append(renderer) pan = PanTool() zoom_in = ZoomInTool() zoom_out = ZoomOutTool() wheel_zoom = WheelZoomTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() save = SaveTool() reset = ResetTool() tools = [ pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset ] plot.add_tools(*tools) col.children.append(plot) objects |= set([ xdr, ydr, xaxis, xaxis.major_label_policy, yaxis, yaxis.major_label_policy, xgrid, ygrid, renderer, renderer.view, glyph, source, source.selected, source.selection_policy, plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title, box_zoom.overlay, box_select.overlay, ] + tickers + tools) return col, objects
var result = new Float64Array(xs.length) for (var i = 0; i < xs.length; i++) { result[i] = provider.graph_layout[xs[i]][%s] } return result """ xcoord = CustomJSTransform(v_func=code % "0", args=dict(provider=graph_renderer.layout_provider)) ycoord = CustomJSTransform(v_func=code % "1", args=dict(provider=graph_renderer.layout_provider)) # Use the transforms to supply coords to a LabelSet labels = LabelSet(x=transform('index', xcoord), y=transform('index', ycoord), text='name', text_font_size="12px", x_offset=-10, y_offset=-5, source=source, render_mode='canvas') plot.add_layout(labels) graph_renderer.selection_policy = NodesAndLinkedEdges() graph_renderer.inspection_policy = EdgesAndLinkedNodes() plot.renderers.append(graph_renderer) # -------------------- save and draw in a file part -------------------- output_file("./myFavoriteWords.html") show(plot) print('-------------------- FINISH Mind_Map_Project using PYTHON --------------------')
def make_example_datatable(): source = ColumnDataSource(mpg) print(source.column_names) manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, editable=True, width=1000) plot = Plot(title=None, x_range=DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = plot.add_glyph(source, cty_glyph) hwy = plot.add_glyph(source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width') plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) layout = Column(plot, data_table) doc = Document() doc.add_root(layout) return doc
x = np.linspace(-2 * pi, 2 * pi, 1000) y = sin(x) z = cos(x) source = ColumnDataSource(data=dict(x=x, y=y)) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, min_border=50) line_glyph = Line(x="x", y="y", line_color="blue") line = plot.add_glyph(source, line_glyph) plot.add_layout(LinearAxis(), 'above') plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') plot.add_layout(LinearAxis(), 'right') pan = PanTool() wheel_zoom = WheelZoomTool() preview_save = PreviewSaveTool() plot.add_tools(pan, wheel_zoom, preview_save) from bokeh.core.enums import LegendLocation for location in LegendLocation: legend = Legend(legends=[(location, [line])], location=location) plot.add_layout(legend)
def create(): det_data = {} fit_params = {} js_data = ColumnDataSource( data=dict(content=["", ""], fname=["", ""], ext=["", ""])) def proposal_textinput_callback(_attr, _old, new): proposal = new.strip() for zebra_proposals_path in pyzebra.ZEBRA_PROPOSALS_PATHS: proposal_path = os.path.join(zebra_proposals_path, proposal) if os.path.isdir(proposal_path): # found it break else: raise ValueError(f"Can not find data for proposal '{proposal}'.") file_list = [] for file in os.listdir(proposal_path): if file.endswith((".ccl", ".dat")): file_list.append((os.path.join(proposal_path, file), file)) file_select.options = file_list file_open_button.disabled = False file_append_button.disabled = False proposal_textinput = TextInput(title="Proposal number:", width=210) proposal_textinput.on_change("value", proposal_textinput_callback) def _init_datatable(): scan_list = [s["idx"] for s in det_data] hkl = [f'{s["h"]} {s["k"]} {s["l"]}' for s in det_data] export = [s.get("active", True) for s in det_data] scan_table_source.data.update( scan=scan_list, hkl=hkl, fit=[0] * len(scan_list), export=export, ) scan_table_source.selected.indices = [] scan_table_source.selected.indices = [0] merge_options = [(str(i), f"{i} ({idx})") for i, idx in enumerate(scan_list)] merge_from_select.options = merge_options merge_from_select.value = merge_options[0][0] file_select = MultiSelect(title="Available .ccl/.dat files:", width=210, height=250) def file_open_button_callback(): nonlocal det_data det_data = [] for f_name in file_select.value: with open(f_name) as file: base, ext = os.path.splitext(f_name) if det_data: append_data = pyzebra.parse_1D(file, ext) pyzebra.normalize_dataset(append_data, monitor_spinner.value) pyzebra.merge_datasets(det_data, append_data) else: det_data = pyzebra.parse_1D(file, ext) pyzebra.normalize_dataset(det_data, monitor_spinner.value) pyzebra.merge_duplicates(det_data) js_data.data.update(fname=[base, base]) _init_datatable() append_upload_button.disabled = False file_open_button = Button(label="Open New", width=100, disabled=True) file_open_button.on_click(file_open_button_callback) def file_append_button_callback(): for f_name in file_select.value: with open(f_name) as file: _, ext = os.path.splitext(f_name) append_data = pyzebra.parse_1D(file, ext) pyzebra.normalize_dataset(append_data, monitor_spinner.value) pyzebra.merge_datasets(det_data, append_data) _init_datatable() file_append_button = Button(label="Append", width=100, disabled=True) file_append_button.on_click(file_append_button_callback) def upload_button_callback(_attr, _old, new): nonlocal det_data det_data = [] for f_str, f_name in zip(new, upload_button.filename): with io.StringIO(base64.b64decode(f_str).decode()) as file: base, ext = os.path.splitext(f_name) if det_data: append_data = pyzebra.parse_1D(file, ext) pyzebra.normalize_dataset(append_data, monitor_spinner.value) pyzebra.merge_datasets(det_data, append_data) else: det_data = pyzebra.parse_1D(file, ext) pyzebra.normalize_dataset(det_data, monitor_spinner.value) pyzebra.merge_duplicates(det_data) js_data.data.update(fname=[base, base]) _init_datatable() append_upload_button.disabled = False upload_div = Div(text="or upload new .ccl/.dat files:", margin=(5, 5, 0, 5)) upload_button = FileInput(accept=".ccl,.dat", multiple=True, width=200) upload_button.on_change("value", upload_button_callback) def append_upload_button_callback(_attr, _old, new): for f_str, f_name in zip(new, append_upload_button.filename): with io.StringIO(base64.b64decode(f_str).decode()) as file: _, ext = os.path.splitext(f_name) append_data = pyzebra.parse_1D(file, ext) pyzebra.normalize_dataset(append_data, monitor_spinner.value) pyzebra.merge_datasets(det_data, append_data) _init_datatable() append_upload_div = Div(text="append extra files:", margin=(5, 5, 0, 5)) append_upload_button = FileInput(accept=".ccl,.dat", multiple=True, width=200, disabled=True) append_upload_button.on_change("value", append_upload_button_callback) def monitor_spinner_callback(_attr, old, new): if det_data: pyzebra.normalize_dataset(det_data, new) _update_plot(_get_selected_scan()) monitor_spinner = Spinner(title="Monitor:", mode="int", value=100_000, low=1, width=145) monitor_spinner.on_change("value", monitor_spinner_callback) def _update_table(): fit_ok = [(1 if "fit" in scan else 0) for scan in det_data] scan_table_source.data.update(fit=fit_ok) def _update_plot(scan): scan_motor = scan["scan_motor"] y = scan["counts"] x = scan[scan_motor] plot.axis[0].axis_label = scan_motor plot_scatter_source.data.update(x=x, y=y, y_upper=y + np.sqrt(y), y_lower=y - np.sqrt(y)) fit = scan.get("fit") if fit is not None: x_fit = np.linspace(x[0], x[-1], 100) plot_fit_source.data.update(x=x_fit, y=fit.eval(x=x_fit)) x_bkg = [] y_bkg = [] xs_peak = [] ys_peak = [] comps = fit.eval_components(x=x_fit) for i, model in enumerate(fit_params): if "linear" in model: x_bkg = x_fit y_bkg = comps[f"f{i}_"] elif any(val in model for val in ("gaussian", "voigt", "pvoigt")): xs_peak.append(x_fit) ys_peak.append(comps[f"f{i}_"]) plot_bkg_source.data.update(x=x_bkg, y=y_bkg) plot_peak_source.data.update(xs=xs_peak, ys=ys_peak) fit_output_textinput.value = fit.fit_report() else: plot_fit_source.data.update(x=[], y=[]) plot_bkg_source.data.update(x=[], y=[]) plot_peak_source.data.update(xs=[], ys=[]) fit_output_textinput.value = "" # Main plot plot = Plot( x_range=DataRange1d(), y_range=DataRange1d(only_visible=True), plot_height=470, plot_width=700, ) plot.add_layout(LinearAxis(axis_label="Counts"), place="left") plot.add_layout(LinearAxis(axis_label="Scan motor"), place="below") plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) plot_scatter_source = ColumnDataSource( dict(x=[0], y=[0], y_upper=[0], y_lower=[0])) plot_scatter = plot.add_glyph( plot_scatter_source, Scatter(x="x", y="y", line_color="steelblue")) plot.add_layout( Whisker(source=plot_scatter_source, base="x", upper="y_upper", lower="y_lower")) plot_fit_source = ColumnDataSource(dict(x=[0], y=[0])) plot_fit = plot.add_glyph(plot_fit_source, Line(x="x", y="y")) plot_bkg_source = ColumnDataSource(dict(x=[0], y=[0])) plot_bkg = plot.add_glyph( plot_bkg_source, Line(x="x", y="y", line_color="green", line_dash="dashed")) plot_peak_source = ColumnDataSource(dict(xs=[[0]], ys=[[0]])) plot_peak = plot.add_glyph( plot_peak_source, MultiLine(xs="xs", ys="ys", line_color="red", line_dash="dashed")) fit_from_span = Span(location=None, dimension="height", line_dash="dashed") plot.add_layout(fit_from_span) fit_to_span = Span(location=None, dimension="height", line_dash="dashed") plot.add_layout(fit_to_span) plot.add_layout( Legend( items=[ ("data", [plot_scatter]), ("best fit", [plot_fit]), ("peak", [plot_peak]), ("linear", [plot_bkg]), ], location="top_left", click_policy="hide", )) plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) plot.toolbar.logo = None # Scan select def scan_table_select_callback(_attr, old, new): if not new: # skip empty selections return # Avoid selection of multiple indicies (via Shift+Click or Ctrl+Click) if len(new) > 1: # drop selection to the previous one scan_table_source.selected.indices = old return if len(old) > 1: # skip unnecessary update caused by selection drop return _update_plot(det_data[new[0]]) def scan_table_source_callback(_attr, _old, _new): _update_preview() scan_table_source = ColumnDataSource( dict(scan=[], hkl=[], fit=[], export=[])) scan_table_source.on_change("data", scan_table_source_callback) scan_table = DataTable( source=scan_table_source, columns=[ TableColumn(field="scan", title="Scan", width=50), TableColumn(field="hkl", title="hkl", width=100), TableColumn(field="fit", title="Fit", width=50), TableColumn(field="export", title="Export", editor=CheckboxEditor(), width=50), ], width=310, # +60 because of the index column height=350, autosize_mode="none", editable=True, ) scan_table_source.selected.on_change("indices", scan_table_select_callback) def _get_selected_scan(): return det_data[scan_table_source.selected.indices[0]] merge_from_select = Select(title="scan:", width=145) def merge_button_callback(): scan_into = _get_selected_scan() scan_from = det_data[int(merge_from_select.value)] if scan_into is scan_from: print("WARNING: Selected scans for merging are identical") return pyzebra.merge_scans(scan_into, scan_from) _update_plot(_get_selected_scan()) merge_button = Button(label="Merge into current", width=145) merge_button.on_click(merge_button_callback) def restore_button_callback(): pyzebra.restore_scan(_get_selected_scan()) _update_plot(_get_selected_scan()) restore_button = Button(label="Restore scan", width=145) restore_button.on_click(restore_button_callback) def fit_from_spinner_callback(_attr, _old, new): fit_from_span.location = new fit_from_spinner = Spinner(title="Fit from:", width=145) fit_from_spinner.on_change("value", fit_from_spinner_callback) def fit_to_spinner_callback(_attr, _old, new): fit_to_span.location = new fit_to_spinner = Spinner(title="to:", width=145) fit_to_spinner.on_change("value", fit_to_spinner_callback) def fitparams_add_dropdown_callback(click): # bokeh requires (str, str) for MultiSelect options new_tag = f"{click.item}-{fitparams_select.tags[0]}" fitparams_select.options.append((new_tag, click.item)) fit_params[new_tag] = fitparams_factory(click.item) fitparams_select.tags[0] += 1 fitparams_add_dropdown = Dropdown( label="Add fit function", menu=[ ("Linear", "linear"), ("Gaussian", "gaussian"), ("Voigt", "voigt"), ("Pseudo Voigt", "pvoigt"), # ("Pseudo Voigt1", "pseudovoigt1"), ], width=145, ) fitparams_add_dropdown.on_click(fitparams_add_dropdown_callback) def fitparams_select_callback(_attr, old, new): # Avoid selection of multiple indicies (via Shift+Click or Ctrl+Click) if len(new) > 1: # drop selection to the previous one fitparams_select.value = old return if len(old) > 1: # skip unnecessary update caused by selection drop return if new: fitparams_table_source.data.update(fit_params[new[0]]) else: fitparams_table_source.data.update( dict(param=[], value=[], vary=[], min=[], max=[])) fitparams_select = MultiSelect(options=[], height=120, width=145) fitparams_select.tags = [0] fitparams_select.on_change("value", fitparams_select_callback) def fitparams_remove_button_callback(): if fitparams_select.value: sel_tag = fitparams_select.value[0] del fit_params[sel_tag] for elem in fitparams_select.options: if elem[0] == sel_tag: fitparams_select.options.remove(elem) break fitparams_select.value = [] fitparams_remove_button = Button(label="Remove fit function", width=145) fitparams_remove_button.on_click(fitparams_remove_button_callback) def fitparams_factory(function): if function == "linear": params = ["slope", "intercept"] elif function == "gaussian": params = ["amplitude", "center", "sigma"] elif function == "voigt": params = ["amplitude", "center", "sigma", "gamma"] elif function == "pvoigt": params = ["amplitude", "center", "sigma", "fraction"] elif function == "pseudovoigt1": params = ["amplitude", "center", "g_sigma", "l_sigma", "fraction"] else: raise ValueError("Unknown fit function") n = len(params) fitparams = dict( param=params, value=[None] * n, vary=[True] * n, min=[None] * n, max=[None] * n, ) if function == "linear": fitparams["value"] = [0, 1] fitparams["vary"] = [False, True] fitparams["min"] = [None, 0] elif function == "gaussian": fitparams["min"] = [0, None, None] return fitparams fitparams_table_source = ColumnDataSource( dict(param=[], value=[], vary=[], min=[], max=[])) fitparams_table = DataTable( source=fitparams_table_source, columns=[ TableColumn(field="param", title="Parameter"), TableColumn(field="value", title="Value", editor=NumberEditor()), TableColumn(field="vary", title="Vary", editor=CheckboxEditor()), TableColumn(field="min", title="Min", editor=NumberEditor()), TableColumn(field="max", title="Max", editor=NumberEditor()), ], height=200, width=350, index_position=None, editable=True, auto_edit=True, ) # start with `background` and `gauss` fit functions added fitparams_add_dropdown_callback(types.SimpleNamespace(item="linear")) fitparams_add_dropdown_callback(types.SimpleNamespace(item="gaussian")) fitparams_select.value = ["gaussian-1"] # add selection to gauss fit_output_textinput = TextAreaInput(title="Fit results:", width=750, height=200) def proc_all_button_callback(): for scan, export in zip(det_data, scan_table_source.data["export"]): if export: pyzebra.fit_scan(scan, fit_params, fit_from=fit_from_spinner.value, fit_to=fit_to_spinner.value) pyzebra.get_area( scan, area_method=AREA_METHODS[area_method_radiobutton.active], lorentz=lorentz_checkbox.active, ) _update_plot(_get_selected_scan()) _update_table() proc_all_button = Button(label="Process All", button_type="primary", width=145) proc_all_button.on_click(proc_all_button_callback) def proc_button_callback(): scan = _get_selected_scan() pyzebra.fit_scan(scan, fit_params, fit_from=fit_from_spinner.value, fit_to=fit_to_spinner.value) pyzebra.get_area( scan, area_method=AREA_METHODS[area_method_radiobutton.active], lorentz=lorentz_checkbox.active, ) _update_plot(scan) _update_table() proc_button = Button(label="Process Current", width=145) proc_button.on_click(proc_button_callback) area_method_div = Div(text="Intensity:", margin=(5, 5, 0, 5)) area_method_radiobutton = RadioGroup(labels=["Function", "Area"], active=0, width=145) lorentz_checkbox = CheckboxGroup(labels=["Lorentz Correction"], width=145, margin=(13, 5, 5, 5)) export_preview_textinput = TextAreaInput(title="Export file preview:", width=500, height=400) def _update_preview(): with tempfile.TemporaryDirectory() as temp_dir: temp_file = temp_dir + "/temp" export_data = [] for s, export in zip(det_data, scan_table_source.data["export"]): if export: export_data.append(s) pyzebra.export_1D( export_data, temp_file, export_target_select.value, hkl_precision=int(hkl_precision_select.value), ) exported_content = "" file_content = [] for ext in EXPORT_TARGETS[export_target_select.value]: fname = temp_file + ext if os.path.isfile(fname): with open(fname) as f: content = f.read() exported_content += f"{ext} file:\n" + content else: content = "" file_content.append(content) js_data.data.update(content=file_content) export_preview_textinput.value = exported_content def export_target_select_callback(_attr, _old, new): js_data.data.update(ext=EXPORT_TARGETS[new]) _update_preview() export_target_select = Select(title="Export target:", options=list(EXPORT_TARGETS.keys()), value="fullprof", width=80) export_target_select.on_change("value", export_target_select_callback) js_data.data.update(ext=EXPORT_TARGETS[export_target_select.value]) def hkl_precision_select_callback(_attr, _old, _new): _update_preview() hkl_precision_select = Select(title="hkl precision:", options=["2", "3", "4"], value="2", width=80) hkl_precision_select.on_change("value", hkl_precision_select_callback) save_button = Button(label="Download File(s)", button_type="success", width=200) save_button.js_on_click( CustomJS(args={"js_data": js_data}, code=javaScript)) fitpeak_controls = row( column(fitparams_add_dropdown, fitparams_select, fitparams_remove_button), fitparams_table, Spacer(width=20), column(fit_from_spinner, lorentz_checkbox, area_method_div, area_method_radiobutton), column(fit_to_spinner, proc_button, proc_all_button), ) scan_layout = column( scan_table, row(monitor_spinner, column(Spacer(height=19), restore_button)), row(column(Spacer(height=19), merge_button), merge_from_select), ) import_layout = column( proposal_textinput, file_select, row(file_open_button, file_append_button), upload_div, upload_button, append_upload_div, append_upload_button, ) export_layout = column( export_preview_textinput, row(export_target_select, hkl_precision_select, column(Spacer(height=19), row(save_button))), ) tab_layout = column( row(import_layout, scan_layout, plot, Spacer(width=30), export_layout), row(fitpeak_controls, fit_output_textinput), ) return Panel(child=tab_layout, title="ccl integrate")
def make_graph_plot(self): """ Builds the graph portion of the final model from the DAG constructed by make_graph. """ nodes = nx.nx_pydot.graphviz_layout(self._graph, prog="dot") node_x, node_y = zip(*nodes.values()) models = [self._graph.nodes[x]["model"] for x in nodes] node_id = list(nodes.keys()) node_source = ColumnDataSource({ "x": node_x, "y": node_y, "index": node_id, "model": models }) edge_x_coords = [] edge_y_coords = [] for start_node, end_node in self._graph.edges: edge_x_coords.extend([[nodes[start_node][0], nodes[end_node][0]]]) edge_y_coords.extend([[nodes[start_node][1], nodes[end_node][1]]]) edge_source = ColumnDataSource({ "xs": edge_x_coords, "ys": edge_y_coords }) p2 = Plot(outline_line_alpha=0.0) xinterval = max(max(node_x) - min(node_x), 200) yinterval = max(max(node_y) - min(node_y), 200) p2.x_range = Range1d(start=min(node_x) - 0.15 * xinterval, end=max(node_x) + 0.15 * xinterval) p2.y_range = Range1d(start=min(node_y) - 0.15 * yinterval, end=max(node_y) + 0.15 * yinterval) node_renderer = GlyphRenderer( data_source=node_source, glyph=Circle(x="x", y="y", size=15, fill_color="lightblue"), nonselection_glyph=Circle(x="x", y="y", size=15, fill_color="lightblue"), selection_glyph=Circle(x="x", y="y", size=15, fill_color="green"), ) edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine(xs="xs", ys="ys")) node_hover_tool = HoverTool(tooltips=[("id", "@index"), ("model", "@model")]) node_hover_tool.renderers = [node_renderer] tap_tool = TapTool() tap_tool.renderers = [node_renderer] labels = LabelSet( x="x", y="y", text="model", source=node_source, text_font_size="8pt", x_offset=-20, y_offset=7, ) help = Label( x=20, y=20, x_units="screen", y_units="screen", text_font_size="8pt", text_font_style="italic", text="Click on a model to see its attributes", ) p2.add_layout(help) p2.add_layout(edge_renderer) p2.add_layout(node_renderer) p2.tools.extend( [node_hover_tool, tap_tool, BoxZoomTool(), ResetTool(), PanTool()]) p2.renderers.append(labels) self._node_source = node_source self._edge_source = edge_source return p2
def draw_network_graph_given(self, edges, nodes, probsa, vdata, eOnly): # probs = dict key: nodename, value: dict(probname:probval) probs = dict() if not eOnly: for nam in nodes: if not nam in probsa: cond = "[]" else: cond = probsa[nam] probs[nam] = dict() try: cur_dist = vdata[nam]["cprob"][cond] #print("No cprob given.") except: pass for i in range(len(vdata[nam]["vals"])): try: probs[nam][vdata[nam]["vals"][i]] = cur_dist[i] except: pass G = nx.DiGraph() if not nodes: nodes = [] for e in edges: if e[0] not in nodes: nodes.append(e[0]) if e[1] not in nodes: nodes.append(e[1]) if eOnly: edges_new = [] for e in edges: if e[0] in nodes and e[1] in nodes: edges_new.append(e) edges = edges_new G.add_edges_from(edges, weight="") #edge_labels=dict([((u,v,),d['weight']) # for u,v,d in G.edges(data=True)]) #edge_colors = len(G.edges())*['black'] #pos=nx.shell_layout(G) # circular_layout random_layout shell_layout spring_layout spectral_layout #nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels) #nx.draw(G,pos, node_size=3000,edge_color=edge_colors) #labels ={} #for n in nodes: # labels[n] = n #nx.draw_networkx_labels(G, pos, labels, font_size=10) # PLOT plot = Plot(plot_width=1300, plot_height=800, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) plot.title.text = "Temporal Dependency Bayesian Network" hover = HoverTool(tooltips=[ ("desc", "@desc"), ]) plot.add_tools(hover, TapTool(), BoxSelectTool()) plot.add_tools(WheelZoomTool()) plot.add_tools(PanTool()) graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0)) desc_probs = [] for n in nodes: try: nodeCur = probs[n] pr = "" for k in nodeCur.keys(): pr += "\nP(" + str(k) + ")=" + str(nodeCur[k]) + "" desc_probs += [pr] except: desc_probs += [""] node_source = ColumnDataSource(data=dict(index=nodes, desc=desc_probs)) graph_renderer.node_renderer.data_source.data = node_source.data graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0]) graph_renderer.node_renderer.selection_glyph = Circle( size=15, fill_color=Spectral4[2]) graph_renderer.node_renderer.hover_glyph = Circle( size=15, fill_color=Spectral4[1]) graph_renderer.edge_renderer.glyph = MultiLine(line_color="firebrick", line_alpha=0.8, line_width=1.1) graph_renderer.edge_renderer.selection_glyph = MultiLine( line_color=Spectral4[2], line_width=5) graph_renderer.edge_renderer.hover_glyph = MultiLine( line_color=Spectral4[1], line_width=5) plot.renderers.append(graph_renderer) graph_renderer.selection_policy = NodesAndLinkedEdges() #graph_renderer.inspection_policy = EdgesAndLinkedNodes() # PLOT ARROWS FOR EDGES pos_dict = graph_renderer.layout_provider.graph_layout done = [] for e in edges: plot.add_layout( Arrow(end=VeeHead(line_width=2, size=4), x_start=pos_dict[e[0]][0], y_start=pos_dict[e[0]][1], x_end=pos_dict[e[1]][0], y_end=pos_dict[e[1]][1])) font_size = "8pt" if not str(e[0]) in done: done += [str(e[0])] plot.add_layout( Label(x=pos_dict[e[0]][0], y=pos_dict[e[0]][1] + 0.01, text=str(e[0]), text_font_size=font_size, render_mode='css', background_fill_alpha=1.0)) if not str(e[1]) in done: done += [str(e[1])] plot.add_layout( Label(x=pos_dict[e[1]][0], y=pos_dict[e[1]][1] + 0.01, text=str(e[1]), text_font_size=font_size, render_mode='css', background_fill_alpha=1.0)) graph_renderer.edge_renderer.glyph.line_join = 'round' output_file("interactive_graphs.html") show(plot) return
from bokeh.io import curdoc, show from bokeh.models import ColumnDataSource, Grid, HexDot, LinearAxis, Plot N = 9 x = np.linspace(-2, 2, N) y = x**2 sizes = np.linspace(10, 20, N) source = ColumnDataSource(dict(x=x, y=y, sizes=sizes)) plot = Plot( title=None, plot_width=300, plot_height=300, min_border=0, toolbar_location=None) glyph = HexDot(x="x", y="y", size="sizes", line_color="#dd1c77", fill_color=None) plot.add_glyph(source, glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) curdoc().add_root(plot) show(plot)
def __init__(self, **kwargs): self.source = ColumnDataSource( data={ 'time': [], 'cpu': [], 'memory_percent': [], 'network-send': [], 'network-recv': [] }) x_range = DataRange1d(follow='end', follow_interval=30000, range_padding=0) resource_plot = Plot(x_range=x_range, y_range=Range1d(start=0, end=1), toolbar_location=None, min_border_bottom=10, **kwargs) line_opts = dict(line_width=2, line_alpha=0.8) g1 = resource_plot.add_glyph( self.source, Line(x='time', y='memory_percent', line_color="#33a02c", **line_opts)) g2 = resource_plot.add_glyph( self.source, Line(x='time', y='cpu', line_color="#1f78b4", **line_opts)) resource_plot.add_layout( LinearAxis(formatter=NumeralTickFormatter(format="0 %")), 'left') legend_opts = dict(location='top_left', orientation='horizontal', padding=5, margin=5, label_height=5) resource_plot.add_layout( Legend(items=[('Memory', [g1]), ('CPU', [g2])], **legend_opts)) network_plot = Plot(x_range=x_range, y_range=DataRange1d(start=0), toolbar_location=None, **kwargs) g1 = network_plot.add_glyph( self.source, Line(x='time', y='network-send', line_color="#a6cee3", **line_opts)) g2 = network_plot.add_glyph( self.source, Line(x='time', y='network-recv', line_color="#b2df8a", **line_opts)) network_plot.add_layout(DatetimeAxis(axis_label="Time"), "below") network_plot.add_layout(LinearAxis(axis_label="MB/s"), 'left') network_plot.add_layout( Legend(items=[('Network Send', [g1]), ('Network Recv', [g2])], **legend_opts)) tools = [ PanTool(dimensions='width'), WheelZoomTool(dimensions='width'), BoxZoomTool(), ResetTool() ] if 'sizing_mode' in kwargs: sizing_mode = {'sizing_mode': kwargs['sizing_mode']} else: sizing_mode = {} combo_toolbar = ToolbarBox(tools=tools, logo=None, toolbar_location='right', **sizing_mode) self.root = row(column(resource_plot, network_plot, **sizing_mode), column(combo_toolbar, **sizing_mode), id='bk-resource-profiles-plot', **sizing_mode) # Required for update callback self.resource_index = [0]
class Population(object): year = 2010 location = "World" def __init__(self): from bokeh.models import ColumnDataSource from bokeh.document import Document # from bokeh.session import Session from bokeh.sampledata.population import load_population self.document = curdoc() #Document() self.session = session # self.session = Session() # self.session.use_doc('population_reveal') # self.session.load_document(self.document) self.df = load_population() self.source_pyramid = ColumnDataSource(data=dict()) # just render at the initialization self._render() def _render(self): self.pyramid_plot() self.create_layout() self.document.add(self.layout) self.update_pyramid() def pyramid_plot(self): from bokeh.models import (Plot, DataRange1d, LinearAxis, Grid, Legend, SingleIntervalTicker) from bokeh.models.glyphs import Quad xdr = DataRange1d() ydr = DataRange1d() self.plot = Plot(title="Widgets", x_range=xdr, y_range=ydr, plot_width=600, plot_height=600) xaxis = LinearAxis() self.plot.add_layout(xaxis, 'below') yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=5)) self.plot.add_layout(yaxis, 'left') self.plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) self.plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) male_quad = Quad(left="male", right=0, bottom="groups", top="shifted", fill_color="#3B8686") male_quad_glyph = self.plot.add_glyph(self.source_pyramid, male_quad) female_quad = Quad(left=0, right="female", bottom="groups", top="shifted", fill_color="#CFF09E") female_quad_glyph = self.plot.add_glyph(self.source_pyramid, female_quad) self.plot.add_layout( Legend(legends=dict(Male=[male_quad_glyph], Female=[female_quad_glyph]))) def on_year_change(self, attr, old, new): self.year = int(new) self.update_pyramid() def on_location_change(self, attr, old, new): self.location = new self.update_pyramid() def create_layout(self): from bokeh.models.widgets import Select, HBox, VBox years = list(map(str, sorted(self.df.Year.unique()))) locations = sorted(self.df.Location.unique()) year_select = Select(title="Year:", value="2010", options=years) location_select = Select(title="Location:", value="World", options=locations) year_select.on_change('value', self.on_year_change) location_select.on_change('value', self.on_location_change) controls = HBox(year_select, location_select) self.layout = VBox(controls, self.plot) def update_pyramid(self): pyramid = self.df[(self.df.Location == self.location) & (self.df.Year == self.year)] male = pyramid[pyramid.Sex == "Male"] female = pyramid[pyramid.Sex == "Female"] total = male.Value.sum() + female.Value.sum() male_percent = -male.Value / total female_percent = female.Value / total groups = male.AgeGrpStart.tolist() shifted = groups[1:] + [groups[-1] + 5] self.source_pyramid.data = dict( groups=groups, shifted=shifted, male=male_percent, female=female_percent, )
def create(palm): fit_max = 1 fit_min = 0 doc = curdoc() # THz calibration plot scan_plot = Plot( title=Title(text="THz calibration"), x_range=DataRange1d(), y_range=DataRange1d(), plot_height=PLOT_CANVAS_HEIGHT, plot_width=PLOT_CANVAS_WIDTH, toolbar_location='right', ) # ---- tools scan_plot.toolbar.logo = None scan_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()) # ---- axes scan_plot.add_layout(LinearAxis(axis_label='Stage delay motor'), place='below') scan_plot.add_layout(LinearAxis(axis_label='Energy shift, eV', major_label_orientation='vertical'), place='left') # ---- grid lines scan_plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) scan_plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- circle cluster glyphs scan_circle_source = ColumnDataSource(dict(x=[], y=[])) scan_plot.add_glyph(scan_circle_source, Circle(x='x', y='y', line_alpha=0, fill_alpha=0.5)) # ---- circle glyphs scan_avg_circle_source = ColumnDataSource(dict(x=[], y=[])) scan_plot.add_glyph( scan_avg_circle_source, Circle(x='x', y='y', line_color='purple', fill_color='purple')) # ---- line glyphs fit_line_source = ColumnDataSource(dict(x=[], y=[])) scan_plot.add_glyph(fit_line_source, Line(x='x', y='y', line_color='purple')) # THz calibration folder path text input def path_textinput_callback(_attr, _old, _new): update_load_dropdown_menu() path_periodic_update() path_textinput = TextInput(title="THz calibration path:", value=os.path.join(os.path.expanduser('~')), width=510) path_textinput.on_change('value', path_textinput_callback) # THz calibration eco scans dropdown def scans_dropdown_callback(_attr, _old, new): scans_dropdown.label = new scans_dropdown = Dropdown(label="ECO scans", button_type='default', menu=[]) scans_dropdown.on_change('value', scans_dropdown_callback) # ---- eco scans periodic update def path_periodic_update(): new_menu = [] if os.path.isdir(path_textinput.value): for entry in os.scandir(path_textinput.value): if entry.is_file() and entry.name.endswith('.json'): new_menu.append((entry.name, entry.name)) scans_dropdown.menu = sorted(new_menu, reverse=True) doc.add_periodic_callback(path_periodic_update, 5000) # Calibrate button def calibrate_button_callback(): palm.calibrate_thz( path=os.path.join(path_textinput.value, scans_dropdown.value)) fit_max_textinput.value = str( np.ceil(palm.thz_calib_data.index.values.max())) fit_min_textinput.value = str( np.floor(palm.thz_calib_data.index.values.min())) update_calibration_plot() def update_calibration_plot(): scan_plot.xaxis.axis_label = '{}, {}'.format(palm.thz_motor_name, palm.thz_motor_unit) scan_circle_source.data.update( x=np.repeat(palm.thz_calib_data.index, palm.thz_calib_data['peak_shift'].apply(len)).tolist(), y=np.concatenate( palm.thz_calib_data['peak_shift'].values).tolist(), ) scan_avg_circle_source.data.update( x=palm.thz_calib_data.index.tolist(), y=palm.thz_calib_data['peak_shift_mean'].tolist()) x = np.linspace(fit_min, fit_max, 100) y = palm.thz_slope * x + palm.thz_intersect fit_line_source.data.update(x=np.round(x, decimals=5), y=np.round(y, decimals=5)) calib_const_div.text = """ thz_slope = {} """.format(palm.thz_slope) calibrate_button = Button(label="Calibrate THz", button_type='default', width=250) calibrate_button.on_click(calibrate_button_callback) # THz fit maximal value text input def fit_max_textinput_callback(_attr, old, new): nonlocal fit_max try: new_value = float(new) if new_value > fit_min: fit_max = new_value palm.calibrate_thz( path=os.path.join(path_textinput.value, scans_dropdown.value), fit_range=(fit_min, fit_max), ) update_calibration_plot() else: fit_max_textinput.value = old except ValueError: fit_max_textinput.value = old fit_max_textinput = TextInput(title='Maximal fit value:', value=str(fit_max)) fit_max_textinput.on_change('value', fit_max_textinput_callback) # THz fit maximal value text input def fit_min_textinput_callback(_attr, old, new): nonlocal fit_min try: new_value = float(new) if new_value < fit_max: fit_min = new_value palm.calibrate_thz( path=os.path.join(path_textinput.value, scans_dropdown.value), fit_range=(fit_min, fit_max), ) update_calibration_plot() else: fit_min_textinput.value = old except ValueError: fit_min_textinput.value = old fit_min_textinput = TextInput(title='Minimal fit value:', value=str(fit_min)) fit_min_textinput.on_change('value', fit_min_textinput_callback) # Save calibration button def save_button_callback(): palm.save_thz_calib(path=path_textinput.value) update_load_dropdown_menu() save_button = Button(label="Save", button_type='default', width=250) save_button.on_click(save_button_callback) # Load calibration button def load_dropdown_callback(_attr, _old, new): palm.load_thz_calib(os.path.join(path_textinput.value, new)) update_calibration_plot() def update_load_dropdown_menu(): new_menu = [] calib_file_ext = '.palm_thz' if os.path.isdir(path_textinput.value): for entry in os.scandir(path_textinput.value): if entry.is_file() and entry.name.endswith((calib_file_ext)): new_menu.append( (entry.name[:-len(calib_file_ext)], entry.name)) load_dropdown.button_type = 'default' load_dropdown.menu = sorted(new_menu, reverse=True) else: load_dropdown.button_type = 'danger' load_dropdown.menu = new_menu doc.add_next_tick_callback(update_load_dropdown_menu) doc.add_periodic_callback(update_load_dropdown_menu, 5000) load_dropdown = Dropdown(label="Load", menu=[], width=250) load_dropdown.on_change('value', load_dropdown_callback) # Calibration constants calib_const_div = Div(text=""" thz_slope = {} """.format(0)) # assemble tab_layout = column( row( scan_plot, Spacer(width=30), column( path_textinput, scans_dropdown, calibrate_button, fit_max_textinput, fit_min_textinput, row(save_button, load_dropdown), calib_const_div, ), )) return Panel(child=tab_layout, title="THz Calibration")
("taylor(%s)" % expr, [line_t_glyph]), ] source.data = dict(x=x, fy=fy, ty=ty) slider.value = order source = ColumnDataSource(data=dict(x=[], fy=[], ty=[])) xdr = Range1d(-7, 7) ydr = Range1d(-20, 200) plot = Plot(x_range=xdr, y_range=ydr, plot_width=800, plot_height=400) line_f = Line(x="x", y="fy", line_color="blue", line_width=2) line_f_glyph = plot.add_glyph(source, line_f) plot.add_layout(line_f_glyph) 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")
text_color='firebrick', text_alpha=0.9, ) label_left = Label( x=0, y=0, text="Label in left panel", x_units='screen', y_units='screen', angle=90, angle_units='deg', text_font_size='24px', text_color='firebrick', text_alpha=0.9, background_fill_color='aliceblue', text_baseline='top', ) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') plot.add_layout(label1) plot.add_layout(label2) plot.add_layout(label3) plot.add_layout(label4) plot.add_layout(label_above, 'above') plot.add_layout(label_left, 'left') save(plot)
plot = Plot(title=title, x_range=xdr, y_range=ydr, plot_width=1000, plot_height=600, toolbar_location=None, outline_line_color=None) xticker = SingleIntervalTicker(interval=5, num_minor_ticks=0) xaxis = LinearAxis(ticker=xticker, axis_line_color=None, major_tick_line_color=None, axis_label="Meters behind 2012 Bolt", axis_label_text_font_size="10pt", axis_label_text_font_style="bold") plot.add_layout(xaxis, "below") xgrid = Grid(dimension=0, ticker=xaxis.ticker, grid_line_dash="dashed") plot.add_layout(xgrid) yticker = SingleIntervalTicker(interval=12, num_minor_ticks=0) yaxis = LinearAxis(ticker=yticker, major_tick_in=-5, major_tick_out=10) plot.add_layout(yaxis, "right") radius = dict(value=5, units="screen") medal_glyph = Circle(x="MetersBack", y="Year", radius=radius, fill_color="MedalFill", line_color="MedalLine", fill_alpha=0.5) medal = plot.add_glyph(source, medal_glyph)
def __init__(self, **kwargs): names = [ 'processes', 'disk-read', 'cores', 'cpu', 'disk-write', 'memory', 'last-seen', 'memory_percent', 'host' ] self.source = ColumnDataSource({k: [] for k in names}) columns = { name: TableColumn(field=name, title=name.replace('_percent', ' %')) for name in names } cnames = [ 'host', 'cores', 'processes', 'memory', 'cpu', 'memory_percent' ] formatters = { 'cpu': NumberFormatter(format='0.0 %'), 'memory_percent': NumberFormatter(format='0.0 %'), 'memory': NumberFormatter(format='0 b'), 'latency': NumberFormatter(format='0.00000'), 'last-seen': NumberFormatter(format='0.000'), 'disk-read': NumberFormatter(format='0 b'), 'disk-write': NumberFormatter(format='0 b'), 'net-send': NumberFormatter(format='0 b'), 'net-recv': NumberFormatter(format='0 b') } table = DataTable( source=self.source, columns=[columns[n] for n in cnames], ) for name in cnames: if name in formatters: table.columns[cnames.index(name)].formatter = formatters[name] mem_plot = Plot(title=Title(text="Memory Usage (%)"), toolbar_location=None, x_range=Range1d(start=0, end=1), y_range=Range1d(start=-0.1, end=0.1), **kwargs) mem_plot.add_glyph( self.source, Circle(x='memory_percent', y=0, size=10, fill_alpha=0.5)) mem_plot.add_layout(LinearAxis(), 'below') hover = HoverTool(point_policy="follow_mouse", tooltips=""" <div> <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span> <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span> </div> """) mem_plot.add_tools(hover, BoxSelectTool()) if 'sizing_mode' in kwargs: sizing_mode = {'sizing_mode': kwargs['sizing_mode']} else: sizing_mode = {} self.root = column(mem_plot, table, id='bk-worker-table', **sizing_mode)
class MemoryUse(DashboardComponent): """ The memory usage across the cluster, grouped by task type """ def __init__(self, scheduler, **kwargs): self.scheduler = scheduler ps = [p for p in scheduler.plugins if isinstance(p, AllProgress)] if ps: self.plugin = ps[0] else: self.plugin = AllProgress(scheduler) self.source = ColumnDataSource(data=dict(name=[], left=[], right=[], center=[], color=[], percent=[], MB=[], text=[])) self.root = Plot(id='bk-nbytes-plot', x_range=DataRange1d(), y_range=DataRange1d(), toolbar_location=None, outline_line_color=None, **kwargs) self.root.add_glyph( self.source, Quad(top=1, bottom=0, left='left', right='right', fill_color='color', fill_alpha=1)) self.root.add_layout(LinearAxis(), 'left') self.root.add_layout(LinearAxis(), 'below') hover = HoverTool(point_policy="follow_mouse", tooltips=""" <div> <span style="font-size: 14px; font-weight: bold;">Name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">Percent:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@percent</span> </div> <div> <span style="font-size: 14px; font-weight: bold;">MB:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@MB</span> </div> """) self.root.add_tools(hover) def update(self): with log_errors(): nb = nbytes_bar(self.plugin.nbytes) update(self.source, nb) self.root.title.text = \ "Memory Use: %0.2f MB" % (sum(self.plugin.nbytes.values()) / 1e6)
def NLD_processing(df): # get original column names from df list_columns_names = df.columns # change the column labels from strings to integers list_columns_int = [] for number in range(0, len(df.index.values)): list_columns_int.append(number) df.columns = list_columns_int # change the rows labels/ indexes from strings to integers df['index'] = list_columns_int df.set_index("index", inplace=True) # Making a function to map color to edges color_palette = list(reversed(Viridis11[:8])) w_max = df.values.max() w_min = df.values.min() step = (w_max - w_min) / (len(color_palette) - 1) colors = [] # Create a graph with 1-way edges for faster painting g = nx.DiGraph() for row in df.index.values: g.add_node(row) for column in df.index.values: if row < column: if (df[row][column] > 0): color_index = int((df[row][column] - w_min) / step) g.add_edge(row, column, weight=df[row][column], color=color_palette[color_index]) colors.append(color_palette[color_index]) weights = [] # Create a separate graph with 2-way edges only to calculate weights g_w = nx.DiGraph() for row in df.index.values: g_w.add_node(row) for column in df.index.values: if row != column: if (df[row][column] > 0): g_w.add_edge(row, column, weight=df[row][column], color=color_palette[color_index]) weights.append(df[row][column]) # do not draw edges with different widths if the max weight is too big if max(weights) > 30: for index, w in enumerate(weights): weights[index] = 1 # loop over all nodes to find neighbors and set min, max, sum for egdes weights connected to a node node_w_dict = {} for n in list_columns_int: node_weight_list = [] for nb in nx.neighbors(g_w, n): node_weight_list.append( nx.get_edge_attributes(g_w, 'weight')[n, nb]) len_list = len(node_weight_list) if len_list != 0: node_min_weight = min(node_weight_list) node_max_weight = max(node_weight_list) node_sum_weight = sum(node_weight_list) node_avr_weight = node_sum_weight / len_list else: node_min_weight = 0 node_max_weight = 0 node_sum_weight = 0 node_avr_weight = 0 node_w_dict.update({ n: { 'minweight': node_min_weight, 'maxweight': node_max_weight, 'avrweight': node_avr_weight, 'sumweight': node_sum_weight } }) nx.set_node_attributes(g, node_w_dict) # Making a function to map node size deg_node_size_list = [ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ] deg_max = max(list(list(zip(*g.degree))[1])) deg_min = min(list(list(zip(*g.degree))[1])) deg_step = (deg_max - deg_min) / (len(deg_node_size_list) - 1) i = 0 node_s_dict = {} for node in list(list(zip(*g.degree))[0]): deg_index = int( (list(list(zip(*g.degree))[1])[i] - deg_min) / deg_step) node_s_dict.update({node: {'nodesize': deg_node_size_list[deg_index]}}) i += 1 nx.set_node_attributes(g, node_s_dict) # create a dictoinary with double for loop mapping = { old_label: new_label for old_label, new_label in itertools.zip_longest( sorted(g.nodes()), list_columns_names, fillvalue=1) } # relabel the names of the nodes from integers back to strings nx.relabel_nodes(g, mapping, copy=False) # Organize common layouts' size for NLD NLD_width = 780 NLD_height = 690 color_mapper = LinearColorMapper(palette=color_palette, low=w_min, high=w_max) color_bar = ColorBar(color_mapper=color_mapper, border_line_color=None, location=(0, 0)) # circular layout plot_circle = Plot(plot_width=NLD_width, plot_height=NLD_height, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) graph_circle = NLD_pocessing_graph(g, weights, colors, nx.circular_layout) NLD_add_tools(plot_circle) plot_circle.add_layout(color_bar, 'right') plot_circle.renderers.append(graph_circle) # spring layout plot_spring = Plot(plot_width=NLD_width, plot_height=NLD_height, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) graph_spring = NLD_pocessing_graph(g, weights, colors, nx.spring_layout) NLD_add_tools(plot_spring) plot_spring.add_layout(color_bar, 'right') plot_spring.renderers.append(graph_spring) # force-directed layout plot_fd = Plot(plot_width=NLD_width, plot_height=NLD_height, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) graph_fd = NLD_FD_pocessing_graph(g, weights, colors) NLD_add_tools(plot_fd) plot_fd.add_layout(color_bar, 'right') plot_fd.renderers.append(graph_fd) # random layout plot_random = Plot(plot_width=NLD_width, plot_height=NLD_height, x_range=Range1d(-0.1, 1.1), y_range=Range1d(-0.1, 1.1)) graph_random = NLD_random_processing_graph(g, weights, colors, nx.random_layout) NLD_add_tools(plot_random) plot_random.add_layout(color_bar, 'right') plot_random.renderers.append(graph_random) # Create panels for each layout circle_panel = Panel(child=plot_circle, title='Circle layout') spring_panel = Panel(child=plot_spring, title='Spring layout') random_panel = Panel(child=plot_random, title='Random layout') fd_panel = Panel(child=plot_fd, title='Force-Directed layout') # Assign NLD panels to Tabs tabsNLD_int = Tabs( tabs=[circle_panel, spring_panel, fd_panel, random_panel]) return tabsNLD_int
class TaskStream(DashboardComponent): """ Task Stream The start and stop time of tasks as they occur on each core of the cluster. """ def __init__(self, n_rectangles=1000, clear_interval=20000, **kwargs): """ kwargs are applied to the bokeh.models.plots.Plot constructor """ self.n_rectangles = n_rectangles self.clear_interval = clear_interval self.last = 0 self.source = ColumnDataSource(data=dict(start=[], duration=[], key=[], name=[], color=[], worker=[], y=[], worker_thread=[], alpha=[])) x_range = DataRange1d() y_range = DataRange1d(range_padding=0) self.root = Plot(title=Title(text="Task Stream"), id='bk-task-stream-plot', x_range=x_range, y_range=y_range, toolbar_location="above", min_border_right=35, **kwargs) self.root.add_glyph( self.source, Rect(x="start", y="y", width="duration", height=0.8, fill_color="color", line_color="color", line_alpha=0.6, fill_alpha="alpha", line_width=3)) self.root.add_layout(DatetimeAxis(axis_label="Time"), "below") ticker = BasicTicker(num_minor_ticks=0) self.root.add_layout( LinearAxis(axis_label="Worker Core", ticker=ticker), "left") self.root.add_layout( Grid(dimension=1, grid_line_alpha=0.4, ticker=ticker)) hover = HoverTool(point_policy="follow_mouse", tooltips=""" <div> <span style="font-size: 12px; font-weight: bold;">@name:</span> <span style="font-size: 10px; font-family: Monaco, monospace;">@duration</span> <span style="font-size: 10px;">ms</span> </div> """) # export = ExportTool() # export.register_plot(self.root) self.root.add_tools( hover, # export, BoxZoomTool(), ResetTool(reset_size=False), PanTool(dimensions="width"), WheelZoomTool(dimensions="width")) # Required for update callback self.task_stream_index = [0] def update(self, messages): with log_errors(): index = messages['task-events']['index'] old = rectangles = messages['task-events']['rectangles'] if not index or index[-1] == self.task_stream_index[0]: return ind = bisect(index, self.task_stream_index[0]) rectangles = { k: [v[i] for i in range(ind, len(index))] for k, v in rectangles.items() } self.task_stream_index[0] = index[-1] # If there has been a significant delay then clear old rectangles if rectangles['start']: m = min(map(add, rectangles['start'], rectangles['duration'])) if m > self.last: self.last, last = m, self.last if m > last + self.clear_interval: self.source.data.update(rectangles) return self.source.stream(rectangles, self.n_rectangles)
y = sin(x) # Create an array of times, starting at the current time, and extending # for len(x) number of hours. times = np.arange(len(x)) * 3600000 + time.time() source = ColumnDataSource(data=dict(x=x, y=y, times=times)) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, min_border=80) circle = Circle(x="times", y="y", fill_color="red", size=5, line_color="black") plot.add_glyph(source, circle) plot.add_layout(DatetimeAxis(), 'below') plot.add_layout(DatetimeAxis(), 'left') plot.add_tools(PanTool(), WheelZoomTool()) doc = Document() doc.add(plot) if __name__ == "__main__": filename = "dateaxis.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Date Axis Example")) print("Wrote %s" % filename) view(filename)
axis_line_color='#AAAAAA', major_tick_line_color='#AAAAAA', major_label_text_color='#666666', major_tick_line_cap="round", axis_line_cap="round", axis_line_width=1, major_tick_line_width=1, ) xaxis = LinearAxis(SingleIntervalTicker(interval=1), axis_label="Children per woman (total fertility)", **AXIS_FORMATS) yaxis = LinearAxis(SingleIntervalTicker(interval=20), axis_label="Life expectancy at birth (years)", **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') # ### Add the background year text # We add this first so it is below all the other glyphs text_source = ColumnDataSource({'year': ['%s' % years[0]]}) text = Text(x=2, y=35, text='year', text_font_size='150pt', text_color='#EEEEEE') plot.add_glyph(text_source, text) # Add the circle renderer_source = sources['_%s' % years[0]] circle_glyph = Circle(x='fertility',
plot = Plot(title=None, plot_width=300, plot_height=300, min_border=0, toolbar_location=None) glyph = Quadratic(x0="x", y0="y", x1="xp02", y1="y", cx="xp01", cy="yp01", line_color="#4daf4a", line_width=3) plot.add_glyph(source, glyph) """ xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') """ #plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) #plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) curdoc().add_root(plot) show(plot) import pandas as pd
def make_calendar(year, month, firstweekday="Mon"): firstweekday = list(day_abbrs).index(firstweekday) calendar = Calendar(firstweekday=firstweekday) month_days = [ None if not day else str(day) for day in calendar.itermonthdays(year, month) ] month_weeks = len(month_days) // 7 workday = "linen" weekend = "lightsteelblue" def weekday(date): return (date.weekday() - firstweekday) % 7 def pick_weekdays(days): return [days[i % 7] for i in range(firstweekday, firstweekday + 7)] day_names = pick_weekdays(day_abbrs) week_days = pick_weekdays([workday] * 5 + [weekend] * 2) source = ColumnDataSource(data=dict( days=list(day_names) * month_weeks, weeks=sum([[str(week)] * 7 for week in range(month_weeks)], []), month_days=month_days, day_backgrounds=sum([week_days] * month_weeks, []), )) holidays = [ (date, summary.replace("(US-OPM)", "").strip()) for (date, summary) in us_holidays if date.year == year and date.month == month and "(US-OPM)" in summary ] holidays_source = ColumnDataSource(data=dict( holidays_days=[day_names[weekday(date)] for date, _ in holidays], holidays_weeks=[ str((weekday(date.replace(day=1)) + date.day) // 7) for date, _ in holidays ], month_holidays=[summary for _, summary in holidays], )) xdr = FactorRange(factors=list(day_names)) ydr = FactorRange( factors=list(reversed([str(week) for week in range(month_weeks)]))) x_scale, y_scale = CategoricalScale(), CategoricalScale() plot = Plot(x_range=xdr, y_range=ydr, x_scale=x_scale, y_scale=y_scale, width=300, height=300, outline_line_color=None) plot.title.text = month_names[month] plot.title.text_font_size = "16px" plot.title.text_color = "darkolivegreen" plot.title.offset = 25 plot.min_border_left = 0 plot.min_border_bottom = 5 rect = Rect(x="days", y="weeks", width=0.9, height=0.9, fill_color="day_backgrounds", line_color="silver") plot.add_glyph(source, rect) rect = Rect(x="holidays_days", y="holidays_weeks", width=0.9, height=0.9, fill_color="pink", line_color="indianred") rect_renderer = plot.add_glyph(holidays_source, rect) text = Text(x="days", y="weeks", text="month_days", text_align="center", text_baseline="middle") plot.add_glyph(source, text) xaxis = CategoricalAxis() xaxis.major_label_text_font_size = "11px" xaxis.major_label_standoff = 0 xaxis.major_tick_line_color = None xaxis.axis_line_color = None plot.add_layout(xaxis, 'above') hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[("Holiday", "@month_holidays")]) plot.tools.append(hover_tool) return plot
x_scale=x_scale, y_scale=y_scale, width=600, height=2000) plot.title.text = "CSS3 Color Names" rect = Rect(x="groups", y="names", width=1, height=1, fill_color="colors", line_color=None) rect_renderer = plot.add_glyph(source, rect) xaxis_above = CategoricalAxis(major_label_orientation=pi / 4) plot.add_layout(xaxis_above, 'above') xaxis_below = CategoricalAxis(major_label_orientation=pi / 4) plot.add_layout(xaxis_below, 'below') plot.add_layout(CategoricalAxis(), 'left') url = "http://www.colors.commutercreative.com/@names/" tooltips = """Click the color to go to:<br /><a href="{url}">{url}</a>""".format( url=url) tap = TapTool(renderers=[rect_renderer], callback=OpenURL(url=url)) hover = HoverTool(renderers=[rect_renderer], tooltips=tooltips) plot.tools.extend([tap, hover]) doc = Document()
def create_plot_figure(self, active_tab): """ create a new plot and insert it in given tab. """ #find table name of active tab and its bokeh instances test = active_tab.name#contains csv filename x_sel=active_tab.select_one({'name':'x_sel'}) y_sel=active_tab.select_one({'name':'y_sel'}) y_sel2=active_tab.select_one({'name':'y_sel2'}) plot_df = self.plot_dfs[test] source = ColumnDataSource(plot_df) #Replace entirely p with a new plot p = Plot( x_range=DataRange1d(), y_range=DataRange1d(), plot_height=600, plot_width=600, title=Title(text=self.sel_csv), name='plot') p.add_tools(BoxZoomTool(), SaveTool(), ResetTool(), PanTool(), HoverTool(tooltips=[('x','$x'), ('y','$y')])) #see https://bokeh.github.io/blog/2017/7/5/idiomatic_bokeh/ x_axis = LinearAxis( axis_label = x_sel.value, ticker=BasicTicker(desired_num_ticks =10), name='x_axis') y_axis = LinearAxis( axis_label = y_sel.value, ticker=BasicTicker(desired_num_ticks =10), name='y_axis') #primary y-axis ly = p.add_glyph(source, Line(x=x_sel.value, y=y_sel.value, line_width=2, line_color='black'), name = 'ly' ) p.add_layout(x_axis,'below') p.add_layout(y_axis,'left') p.y_range.renderers = [ly] #secondary y-axis if y_sel2.value.strip() != 'None':#secondary y-axis y_axis2 = LinearAxis( axis_label = y_sel2.value, ticker=BasicTicker(desired_num_ticks=10), name='y_axis2', y_range_name='right_axis') p.add_layout(y_axis2,'right') p.extra_y_ranges = {"right_axis": DataRange1d()} ly2 = p.add_glyph(source, Line(x=x_sel.value, y=y_sel2.value, line_width=2, line_color='red'), y_range_name='right_axis', name = 'ly2' ) p.extra_y_ranges['right_axis'].renderers = [ly2] leg_items = [LegendItem(label=y_sel.value, renderers=[ly]), LegendItem(label=y_sel2.value, renderers=[ly2])] else: leg_items = [LegendItem(label=y_sel.value, renderers=[ly])] p.add_layout(Legend(items=leg_items, location='top_right') ) active_tab.child.children[1] = p return p
def make_calendar(sp500_data_lst, djia_data_lst, nasdaq_data_lst, twitter_data_lst, holiday_lst, nyt_data_lst, approval_data_lst, generic_dem_lst, generic_rep_lst, plot_wid, plot_ht, year, month, firstweekday="Sun"): firstweekday = list(day_abbrs).index(firstweekday) calendar = Calendar(firstweekday=firstweekday) month_days = [ None if not day else str(day) for day in calendar.itermonthdays(year, month) ] month_weeks = len(month_days) // 7 workday = "linen" weekend = "lightsteelblue" def weekday(date): return (date.weekday() - firstweekday) % 7 def pick_weekdays(days): return [days[i % 7] for i in range(firstweekday, firstweekday + 7)] day_names = pick_weekdays(day_abbrs) week_days = pick_weekdays([workday] * 5 + [weekend] * 2) source = ColumnDataSource(data=dict( days=list(day_names) * month_weeks, weeks=sum([[str(week)] * 7 for week in range(month_weeks)], []), month_days=month_days, day_backgrounds=['white'] * len(month_days), )) djia_data = [(dj_date, DJIA) for (dj_date, DJIA) in djia_data_lst if dj_date.year == year and dj_date.month == month] nasdaq_data = [(nas_date, NASDAQCOM) for (nas_date, NASDAQCOM) in nasdaq_data_lst if nas_date.year == year and nas_date.month == month] sp500_data = [(sp500_date, SP500) for (sp500_date, SP500) in sp500_data_lst if sp500_date.year == year and sp500_date.month == month] holidays = [(holiday_date, Holiday) for (holiday_date, Holiday) in holiday_lst if holiday_date.year == year and holiday_date.month == month] twitter_data = [ (twitter_date, topics) for (twitter_date, topics) in twitter_data_lst if twitter_date.year == year and twitter_date.month == month ] nyt_data = [(nyt_date, headlines) for (nyt_date, headlines) in nyt_data_lst if nyt_date.year == year and nyt_date.month == month] approval_data = [ (approval_date, approve_estimate) for (approval_date, approve_estimate) in approval_data_lst if approval_date.year == year and approval_date.month == month ] approval_data.sort() generic_dem = [(generic_date, dem_estimate) for (generic_date, dem_estimate) in generic_dem_lst if generic_date.year == year and generic_date.month == month ] generic_dem.sort() generic_rep = [(generic_date, rep_estimate) for (generic_date, rep_estimate) in generic_rep_lst if generic_date.year == year and generic_date.month == month ] generic_rep.sort() colors_djia = [DJIA for _, DJIA in djia_data] colors_sp500 = [SP500 for _, SP500 in sp500_data] colors_nasdaq = [NASDAQCOM for _, NASDAQCOM in nasdaq_data] for i in range(len(colors_djia) - 1): avg = np.mean([colors_djia[i], colors_sp500[i], colors_nasdaq[i]]) if 0 < avg <= 11000: colors_djia[i] = '#E52700' elif 11000 < avg <= 11100: colors_djia[i] = '#E33A00' elif 11100 < avg <= 11200: colors_djia[i] = '#E14C00' elif 11200 < avg <= 11300: colors_djia[i] = '#DF5E00' elif 11300 < avg <= 11400: colors_djia[i] = '#DD6F00' elif 11400 < avg <= 11500: colors_djia[i] = '#DB8000' elif 11500 < avg <= 11600: colors_djia[i] = '#D99100' elif 11600 < avg <= 11700: colors_djia[i] = '#D7A100' elif 11700 < avg <= 11800: colors_djia[i] = '#D5B100' elif 11800 < avg <= 11900: colors_djia[i] = '#D3C100' elif 11900 < avg <= 12000: colors_djia[i] = '#D1D000' elif 12000 < avg <= 12100: colors_djia[i] = '#BECF00' elif 12200 < avg <= 12300: colors_djia[i] = '#ABCD00' elif 12300 < avg <= 12400: colors_djia[i] = '#99CB00' elif 12400 < avg <= 12500: colors_djia[i] = '#87C900' elif 12500 < avg <= 12600: colors_djia[i] = '#75C700' elif 12500 < avg <= 12600: colors_djia[i] = '#64C500' else: colors_djia[i] = '#53C300' holiday_source = ColumnDataSource(data=dict( month_djia=[DJIA for _, DJIA in djia_data], month_nasdaq=[NASDAQCOM for _, NASDAQCOM in nasdaq_data], month_sp500=[SP500 for _, SP500 in sp500_data], month_twitter=[topics for _, topics in twitter_data], month_holidays=[Holiday for _, Holiday in holidays], nyt_days=[day_names[weekday(nyt_date)] for nyt_date, _ in nyt_data], nyt_weeks=['0'] + [ str((weekday(nyt_date.replace(day=1)) + nyt_date.day) // 7) for nyt_date, _ in nyt_data ], month_nyt=[headlines for _, headlines in nyt_data], month_approval=[ approve_estimate for _, approve_estimate in approval_data ], month_generic_dem=[dem_estimate for _, dem_estimate in generic_dem], month_generic_rep=[rep_estimate for _, rep_estimate in generic_rep], day_backgrounds=colors_djia, )) xdr = FactorRange(factors=list(day_names)) ydr = FactorRange( factors=list(reversed([str(week) for week in range(month_weeks)]))) x_scale, y_scale = CategoricalScale(), CategoricalScale() plot = Plot(x_range=xdr, y_range=ydr, x_scale=x_scale, y_scale=y_scale, plot_width=plot_wid, plot_height=plot_ht) plot.title.text = month_names[month] + " " + str(year) plot.title.text_font_size = "14pt" plot.title.text_color = "black" plot.title.offset = 25 plot.min_border_left = 5 plot.min_border_top = 5 plot.min_border_bottom = 190 plot.border_fill_color = "white" plot.background_fill_alpha = 0.5 plot.border_fill_alpha = 0.3 rect = Rect(x="days", y="weeks", width=0.9, height=0.9, fill_color="day_backgrounds", line_color="silver") plot.add_glyph(source, rect) rect = Rect(x="nyt_days", y="nyt_weeks", width=0.9, fill_color="day_backgrounds", height=0.9) rect_renderer = plot.add_glyph(holiday_source, rect) text = Text(x="days", y="weeks", text="month_days", text_align="center", text_baseline="middle") plot.add_glyph(source, text) xaxis = CategoricalAxis() xaxis.major_label_text_font_size = "10pt" xaxis.major_label_standoff = 0 xaxis.major_tick_line_color = None xaxis.axis_line_color = None plot.add_layout(xaxis, 'above') TOOLTIPS = """ <div style="height:100%; max-width:300px; min-width:200px;background-color: aliceblue; position:relative;"> <div> <span style="font-size: 17px; font-weight: bold;"> Holiday: @month_holidays</span><br> <span style="font-size: 15px; font-weight: bold; color: darkgrey;"> Trump Approval Rating: @month_approval{0,0.0}%</span><br> <span style="font-size: 15px; font-weight: bold; color: blue;"> Generic Democrat: @month_generic_dem{0,0.0}%</span><br> <span style="font-size: 15px; font-weight: bold; color: red;"> Generic Republican: @month_generic_rep{0,0.0}%</span><br> <span style="font-size: 17px; font-weight: bold;"> NASDAQ: @month_nasdaq{0,0.00}</span><br> <span style="font-size: 17px; font-weight: bold;"> DJIA: @month_djia{0,0.00}</span><br> <span style="font-size: 17px; font-weight: bold;">S&P500: @month_sp500{0,0.00}</span><br> </div> <div> <img src="/static/img/nyt_logo.png" height="15" width="15" style="float: left;"></img> </div> <div> <span style="font-size: 17px; font-weight: bold;">NYT Headlines:</span> <span style="font-size: 15px;">@month_nyt</span> </div> <div> <img src="/static/img/twitter_logo.png" height="15" width="15" style="float: left;"></img> </div> <div> <span style="font-size: 17px; color:blue; font-weight: bold;">Trending Tweets:</span> <span style="font-size: 15px; color:blue;">@month_twitter</span> </div> </div> """ hover_tool = HoverTool(renderers=[rect_renderer], tooltips=TOOLTIPS) # hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[("Holiday", "@month_holidays"),("DJIA", "@month_djia{0,0.00}"), # ("NASDAQ", "@month_nasdaq{0,0.00}"),("S&P500", "@month_sp500{0,0.00}"),("NYT Headlines", "@month_nyt"),("Trending Tweets","@month_twitter")]) plot.tools.append(hover_tool) return plot
def __init__( self, plot_height=894, plot_width=854, image_height=100, image_width=100, x_start=None, x_end=None, y_start=None, y_end=None, ): """Initialize image view plot. Args: plot_height (int, optional): Height of plot area in screen pixels. Defaults to 894. plot_width (int, optional): Width of plot area in screen pixels. Defaults to 854. image_height (int, optional): Image height in pixels. Defaults to 100. image_width (int, optional): Image width in pixels. Defaults to 100. x_start (int, optional): Initial x-axis start value. If None, then equals to 0. Defaults to None. x_end (int, optional): Initial x-axis end value. If None, then equals to image_width. Defaults to None. y_start (int, optional): Initial y-axis start value. If None, then equals to 0. Defaults to None. y_end (int, optional): Initial y-axis end value. If None, then equals to image_height. Defaults to None. """ if x_start is None: x_start = 0 if x_end is None: x_end = image_width if y_start is None: y_start = 0 if y_end is None: y_end = image_height self.zoom_views = [] plot = Plot( x_range=Range1d(x_start, x_end, bounds=(0, image_width)), y_range=Range1d(y_start, y_end, bounds=(0, image_height)), plot_height=plot_height, plot_width=plot_width, toolbar_location="left", ) self.plot = plot # ---- tools plot.toolbar.logo = None hovertool = HoverTool(tooltips=[("intensity", "@image")], names=["image_glyph"]) plot.add_tools(PanTool(), WheelZoomTool(maintain_focus=False), SaveTool(), ResetTool(), hovertool) plot.toolbar.active_scroll = plot.tools[1] # ---- axes plot.add_layout(LinearAxis(), place="above") plot.add_layout(LinearAxis(major_label_orientation="vertical"), place="right") # ---- grid lines plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph self._image_source = ColumnDataSource( dict( image=[np.zeros((1, 1), dtype="float32")], x=[x_start], y=[y_start], dw=[x_end - x_start], dh=[y_end - y_start], )) self.image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") image_renderer = plot.add_glyph(self._image_source, self.image_glyph, name="image_glyph") # This avoids double update of image values on a client, see # https://github.com/bokeh/bokeh/issues/7079 # https://github.com/bokeh/bokeh/issues/7299 image_renderer.view.source = ColumnDataSource() # ---- pixel value text glyph self._pvalue_source = ColumnDataSource(dict(x=[], y=[], text=[])) plot.add_glyph( self._pvalue_source, Text( x="x", y="y", text="text", text_align="center", text_baseline="middle", text_color="white", ), ) # ---- horizontal and vertical projection line glyphs self._hproj_source = ColumnDataSource(dict(x=[], y=[])) plot.add_glyph(self._hproj_source, Line(x="x", y="y", line_color="greenyellow")) self._vproj_source = ColumnDataSource(dict(x=[], y=[])) plot.add_glyph(self._vproj_source, Line(x="x", y="y", line_color="greenyellow")) proj_toggle = CheckboxGroup(labels=["Inner Projections"], default_size=145) self.proj_toggle = proj_toggle
x = arange(-2 * pi, 2 * pi, 0.1) y = sin(x) y2 = linspace(0, 100, len(y)) source = ColumnDataSource(data=dict(x=x, y=y, y2=y2)) plot = Plot(x_range=Range1d(start=-6.5, end=6.5), y_range=Range1d(start=-1.1, end=1.1), min_border=80) plot.extra_y_ranges = {"foo": Range1d(start=0, end=100)} circle = Circle(x="x", y="y", fill_color="red", size=5, line_color="black") plot.add_glyph(source, circle) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') circle2 = Circle(x="x", y="y2", fill_color="blue", size=5, line_color="black") plot.add_glyph(source, circle2, y_range_name="foo") plot.add_layout(LinearAxis(y_range_name="foo"), 'left') plot.add_tools(PanTool(), WheelZoomTool()) doc = Document() doc.add(plot) if __name__ == "__main__": filename = "twin_axis.html" with open(filename, "w") as f:
"rgba(120, 230, 150, 0.5)", "rgba(120, 230, 150, 0.5)" ])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) circle = Circle(x="x", y="y", radius=0.2, fill_color="color", line_color="black") circle_renderer = plot.add_glyph(source, circle) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') customjs = CustomJS.from_coffeescript(args=dict(source=source), code=""" Util = require "util/util" data = source.data for i in Util.get_indices(source) color = data['color'][i] window.alert("Selected color: #{color}") """) tap = TapTool(renderers=[circle_renderer], callback=customjs) plot.add_tools(PanTool(), WheelZoomTool(), tap)