def trail_map(data): lon = (min(data.lon) + max(data.lon))/2 lat = (min(data.lat) + max(data.lat))/2 map_options = GMapOptions(lng=lon, lat=lat, zoom=13) plot = GMapPlot(title="%s - Trail Map" % title, map_options=map_options, plot_width=800, plot_height=800) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') xgrid = Grid(plot=plot, dimension=0, ticker=xaxis.ticker, grid_line_dash="dashed", grid_line_color="gray") ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker, grid_line_dash="dashed", grid_line_color="gray") plot.renderers.extend([xgrid, ygrid]) plot.add_tools(PanTool(), WheelZoomTool(), ResetTool(), BoxSelectTool()) line_source = ColumnDataSource(dict(x=data.lon, y=data.lat, dist=data.dist)) line = Line(x="x", y="y", line_color="blue", line_width=2) plot.add_glyph(line_source, line) plot.x_range = DataRange1d(sources=[line_source.columns("x")]) plot.y_range = DataRange1d(sources=[line_source.columns("y")]) return plot
def large_plot(n): from bokeh.models import (Plot, PlotContext, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, BoxSelectionOverlay, ResizeTool, PreviewSaveTool, ResetTool) from bokeh.models.glyphs import Line context = PlotContext() objects = set([context]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis(plot=plot) yaxis = LinearAxis(plot=plot) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) 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(plot=plot) wheel_zoom = WheelZoomTool(plot=plot) box_zoom = BoxZoomTool(plot=plot) box_select = BoxSelectTool(plot=plot) box_selection = BoxSelectionOverlay(tool=box_select) resize = ResizeTool(plot=plot) previewsave = PreviewSaveTool(plot=plot) reset = ResetTool(plot=plot) tools = [ pan, wheel_zoom, box_zoom, box_select, box_selection, resize, previewsave, reset ] plot.tools.append(tools) context.children.append(plot) objects |= set([ source, xdr, ydr, plot, xaxis, yaxis, xgrid, ygrid, renderer, glyph, plot.tool_events ] + tickers + tools) return context, objects
def trail_map(data): lon = (min(data.lon) + max(data.lon)) / 2 lat = (min(data.lat) + max(data.lat)) / 2 map_options = GMapOptions(lng=lon, lat=lat, zoom=13) plot = GMapPlot(title="%s - Trail Map" % title, map_options=map_options, plot_width=800, plot_height=800) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') xgrid = Grid(plot=plot, dimension=0, ticker=xaxis.ticker, grid_line_dash="dashed", grid_line_color="gray") ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker, grid_line_dash="dashed", grid_line_color="gray") plot.renderers.extend([xgrid, ygrid]) hover = HoverTool(tooltips=[("distance", "@dist")]) plot.add_tools(hover, PanTool(), WheelZoomTool(), ResetTool(), BoxSelectTool()) line_source = ColumnDataSource(dict(x=data.lon, y=data.lat, dist=data.dist)) line = Line(x="x", y="y", line_color="blue", line_width=2) plot.add_glyph(line_source, line) plot.x_range = DataRange1d(sources=[line_source.columns("x")]) plot.y_range = DataRange1d(sources=[line_source.columns("y")]) return plot
def altitude_profile(data): plot = Plot(title="%s - Altitude Profile" % title, plot_width=800, plot_height=400) 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(), BoxSelectTool()) 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) plot.x_range = DataRange1d(sources=[line_source.columns("x")]) plot.y_range = DataRange1d(sources=[line_source.columns("y")]) return plot
def altitude_profile(data): plot = Plot(title="%s - Altitude Profile" % title, plot_width=800, plot_height=400) 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(), BoxSelectTool()) 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) plot.x_range = DataRange1d(sources=[line_source.columns("x")]) plot.y_range = DataRange1d(sources=[line_source.columns("y")]) return plot
def large_plot(n): from bokeh.models import (Plot, PlotContext, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, BoxSelectionOverlay, ResizeTool, PreviewSaveTool, ResetTool) from bokeh.models.glyphs import Line context = PlotContext() objects = set([context]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis(plot=plot) yaxis = LinearAxis(plot=plot) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) 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(plot=plot) wheel_zoom = WheelZoomTool(plot=plot) box_zoom = BoxZoomTool(plot=plot) box_select = BoxSelectTool(plot=plot) box_selection = BoxSelectionOverlay(tool=box_select) resize = ResizeTool(plot=plot) previewsave = PreviewSaveTool(plot=plot) reset = ResetTool(plot=plot) tools = [pan, wheel_zoom, box_zoom, box_select, box_selection, resize, previewsave, reset] plot.tools.append(tools) context.children.append(plot) objects |= set([source, xdr, ydr, plot, xaxis, yaxis, xgrid, ygrid, renderer, glyph, plot.tool_events] + tickers + tools) return context, objects
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 = Document() 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(sources=[self.source_pyramid.columns("male"), self.source_pyramid.columns("female")]) ydr = DataRange1d(sources=[self.source_pyramid.columns("groups")]) 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, obj, attr, old, new): self.year = int(new) self.update_pyramid() def on_location_change(self, obj, 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, ) self.session.store_document(self.document)
summer_start = df.Date.irow(summer_start) summer_end = df.Date.irow(summer_end) calendar_end = df.Date.irow(-1) d1 = calendar_start + (summer_start - calendar_start) / 2 d2 = summer_start + (summer_end - summer_start) / 2 d3 = summer_end + (calendar_end - summer_end) / 2 text_source = ColumnDataSource( dict( dates=[d1, d2, d3], times=[dt.time(11, 30)] * 3, texts=["CST (UTC+1)", "CEST (UTC+2)", "CST (UTC+1)"], )) xdr = DataRange1d(sources=[source.columns("dates")]) ydr = DataRange1d(sources=[source.columns("sunrises", "sunsets")]) title = "Daylight Hours - Warsaw, Poland" plot = Plot(title=title, x_range=xdr, y_range=ydr, plot_width=800, plot_height=400) patch1 = Patch(x="dates", y="times", fill_color="skyblue", fill_alpha=0.8) plot.add_glyph(patch1_source, patch1) patch2 = Patch(x="dates", y="times", fill_color="orange", fill_alpha=0.8) plot.add_glyph(patch2_source, patch2)
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) xdr = DataRange1d(sources=[source.columns("index")]) ydr = DataRange1d(sources=[source.columns("cty"), source.columns("hwy")]) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=1000, plot_height=300) xaxis = LinearAxis(plot=plot) plot.below.append(xaxis) yaxis = LinearAxis(plot=plot) ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker) plot.left.append(yaxis) cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8,
from bokeh.document import Document from bokeh.session import Session from bokeh.browserlib import view document = Document() session = Session() session.use_doc('linked_tap_server') session.load_document(document) N = 9 x = np.linspace(-2, 2, N) y = x**2 source1 = ColumnDataSource(dict(x = x, y = y, size = [20]*N)) xdr1 = DataRange1d(sources=[source1.columns("x")]) ydr1 = DataRange1d(sources=[source1.columns("y")]) plot1 = Plot(title="Plot1", x_range=xdr1, y_range=ydr1, plot_width=400, plot_height=400) plot1.tools.append(TapTool(plot=plot1)) plot1.add_glyph(source1, Circle(x="x", y="y", size="size", fill_color="red")) source2 = ColumnDataSource(dict(x = x, y = y, color = ["blue"]*N)) xdr2 = DataRange1d(sources=[source2.columns("x")]) ydr2 = DataRange1d(sources=[source2.columns("y")]) plot2 = Plot(title="Plot2", x_range=xdr2, y_range=ydr2, plot_width=400, plot_height=400) plot2.tools.append(TapTool(plot=plot2)) plot2.add_glyph(source2, Circle(x="x", y="y", size=20, fill_color="color")) def on_selection_change1(obj, attr, _, inds): color = ["blue"]*N if inds:
try: rate = unemployment[county_id] idx = min(int(rate/2), 5) county_colors.append(colors[idx]) except KeyError: county_colors.append("black") county_source = ColumnDataSource( data=dict( county_xs=[us_counties[code]["lons"] for code in us_counties if us_counties[code]["state"] not in ["ak", "hi", "pr", "gu", "vi", "mp", "as"]], county_ys=[us_counties[code]["lats"] for code in us_counties if us_counties[code]["state"] not in ["ak", "hi", "pr", "gu", "vi", "mp", "as"]], county_colors=county_colors ) ) xdr = DataRange1d(sources=[state_source.columns("state_xs")]) ydr = DataRange1d(sources=[state_source.columns("state_ys")]) plot = Plot(x_range=xdr, y_range=ydr, min_border=0, border_fill="white", title="2009 Unemployment Data", plot_width=1300, plot_height=800, toolbar_location="left") county_patches = Patches(xs="county_xs", ys="county_ys", fill_color="county_colors", fill_alpha=0.7, line_color="white", line_width=0.5) plot.add_glyph(county_source, county_patches) state_patches = Patches(xs="state_xs", ys="state_ys", fill_alpha=0.0, line_color="#884444", line_width=2) plot.add_glyph(state_source, state_patches) plot.add_tools(ResizeTool()) doc = Document() doc.add(plot)
from bokeh.document import Document from bokeh.session import Session from bokeh.browserlib import view document = Document() session = Session() session.use_doc('linked_tap_server') session.load_document(document) N = 9 x = np.linspace(-2, 2, N) y = x**2 source1 = ColumnDataSource(dict(x=x, y=y, size=[20] * N)) xdr1 = DataRange1d(sources=[source1.columns("x")]) ydr1 = DataRange1d(sources=[source1.columns("y")]) plot1 = Plot(title="Plot1", x_range=xdr1, y_range=ydr1, plot_width=400, plot_height=400) plot1.tools.append(TapTool(plot=plot1)) plot1.add_glyph(source1, Circle(x="x", y="y", size="size", fill_color="red")) source2 = ColumnDataSource(dict(x=x, y=y, color=["blue"] * N)) xdr2 = DataRange1d(sources=[source2.columns("x")]) ydr2 = DataRange1d(sources=[source2.columns("y")]) plot2 = Plot(title="Plot2", x_range=xdr2, y_range=ydr2,
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) # TODO: rewrite this using plotting API {{{ xdr = DataRange1d(sources=[source.columns("index")]) ydr = DataRange1d(sources=[source.columns("cty"), source.columns("hwy")]) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=1000, plot_height=300) xaxis = LinearAxis(plot=plot) plot.below.append(xaxis) yaxis = LinearAxis(plot=plot) ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker) plot.left.append(yaxis) 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 = GlyphRenderer(data_source=source, glyph=cty_glyph) hwy = GlyphRenderer(data_source=source, glyph=hwy_glyph) tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"),
sprint["Country"] = sprint.Abbrev.map(lambda abbr: abbrev_to_country[abbr]) sprint["Medal"] = sprint.Medal.map(lambda medal: medal.lower()) sprint["Speed"] = 100.0 / sprint.Time sprint["MetersBack"] = 100.0 * (1.0 - t0 / sprint.Time) sprint["MedalFill"] = sprint.Medal.map(lambda medal: fill_color[medal]) sprint["MedalLine"] = sprint.Medal.map(lambda medal: line_color[medal]) sprint["SelectedName"] = sprint[["Name", "Medal", "Year"]].apply( tuple, axis=1).map(lambda args: selected_name(*args)) source = ColumnDataSource(sprint) title = "Usain Bolt vs. 116 years of Olympic sprinters" xdr = Range1d( start=sprint.MetersBack.max() + 2, end=0) # XXX: +2 is poor-man's padding (otherwise misses last tick) ydr = DataRange1d(sources=[source.columns("Year")], rangepadding=0.05) # XXX: should be 2 years (both sides) 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",
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 = Document() 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(sources=[self.source_pyramid.columns("male"), self.source_pyramid.columns("female")]) ydr = DataRange1d(sources=[self.source_pyramid.columns("groups")]) 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, obj, attr, old, new): self.year = int(new) self.update_pyramid() def on_location_change(self, obj, 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, ) self.session.store_document(self.document)
from bokeh.embed import file_html from bokeh.models.glyphs import Circle from bokeh.models import (Plot, DataRange1d, DatetimeAxis, ColumnDataSource, PanTool, WheelZoomTool) from bokeh.resources import INLINE x = arange(-2 * pi, 2 * pi, 0.1) 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(sources=[source.columns("times")]) ydr = DataRange1d(sources=[source.columns("y")]) 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)
calendar_start = df.Date.irow(0) summer_start = df.Date.irow(summer_start) summer_end = df.Date.irow(summer_end) calendar_end = df.Date.irow(-1) d1 = calendar_start + (summer_start - calendar_start)/2 d2 = summer_start + (summer_end - summer_start)/2 d3 = summer_end + (calendar_end - summer_end)/2 text_source = ColumnDataSource(dict( dates = [d1, d2, d3], times = [dt.time(11, 30)]*3, texts = ["CST (UTC+1)", "CEST (UTC+2)", "CST (UTC+1)"], )) xdr = DataRange1d(sources=[source.columns("dates")]) ydr = DataRange1d(sources=[source.columns("sunrises", "sunsets")]) title = "Daylight Hours - Warsaw, Poland" plot = Plot( title=title, x_range=xdr, y_range=ydr, plot_width=800, plot_height=400 ) patch1 = Patch(x="dates", y="times", fill_color="skyblue", fill_alpha=0.8) plot.add_glyph(patch1_source, patch1) patch2 = Patch(x="dates", y="times", fill_color="orange", fill_alpha=0.8) plot.add_glyph(patch2_source, patch2)
t0 = sprint.Time[0] sprint["Abbrev"] = sprint.Country sprint["Country"] = sprint.Abbrev.map(lambda abbr: abbrev_to_country[abbr]) sprint["Medal"] = sprint.Medal.map(lambda medal: medal.lower()) sprint["Speed"] = 100.0/sprint.Time sprint["MetersBack"] = 100.0*(1.0 - t0/sprint.Time) sprint["MedalFill"] = sprint.Medal.map(lambda medal: fill_color[medal]) sprint["MedalLine"] = sprint.Medal.map(lambda medal: line_color[medal]) sprint["SelectedName"] = sprint[["Name", "Medal", "Year"]].apply(tuple, axis=1).map(lambda args: selected_name(*args)) source = ColumnDataSource(sprint) title = "Usain Bolt vs. 116 years of Olympic sprinters" xdr = Range1d(start=sprint.MetersBack.max()+2, end=0) # XXX: +2 is poor-man's padding (otherwise misses last tick) ydr = DataRange1d(sources=[source.columns("Year")], rangepadding=0.05) # XXX: should be 2 years (both sides) 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)
class DataTables(object): def __init__(self): self.document = Document() self.session = Session() self.session.use_doc('data_tables_server') self.session.load_document(self.document) self.manufacturer_filter = None self.model_filter = None self.transmission_filter = None self.drive_filter = None self.class_filter = None self.source = ColumnDataSource() self.update_data() self.document.add(self.create()) self.session.store_document(self.document) def create(self): 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()) manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers) manufacturer_select.on_change('value', self.on_manufacturer_change) model_select = Select(title="Model:", value="All", options=["All"] + models) model_select.on_change('value', self.on_model_change) transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions) transmission_select.on_change('value', self.on_transmission_change) drive_select = Select(title="Drive:", value="All", options=["All"] + drives) drive_select.on_change('value', self.on_drive_change) class_select = Select(title="Class:", value="All", options=["All"] + classes) class_select.on_change('value', self.on_class_change) 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=self.source, columns=columns, editable=True) xdr = DataRange1d(sources=[self.source.columns("index")]) ydr = DataRange1d(sources=[self.source.columns("cty"), self.source.columns("hwy")]) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=300) xaxis = LinearAxis(plot=plot) plot.below.append(xaxis) yaxis = LinearAxis(plot=plot) ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker) plot.left.append(yaxis) 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 = GlyphRenderer(data_source=self.source, glyph=cty_glyph) hwy = GlyphRenderer(data_source=self.source, glyph=hwy_glyph) tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(plot=plot, renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(plot=plot, renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(plot=plot, renderers=[cty, hwy], dimensions=['width']) plot.tools.extend([cty_hover_tool, hwy_hover_tool, select_tool]) plot.renderers.extend([cty, hwy, ygrid]) controls = VBox(children=[manufacturer_select, model_select, transmission_select, drive_select, class_select], width=200) top_panel = HBox(children=[controls, plot]) layout = VBox(children=[top_panel, data_table]) return layout def on_manufacturer_change(self, obj, attr, _, value): self.manufacturer_filter = None if value == "All" else value self.update_data() def on_model_change(self, obj, attr, _, value): self.model_filter = None if value == "All" else value self.update_data() def on_transmission_change(self, obj, attr, _, value): self.transmission_filter = None if value == "All" else value self.update_data() def on_drive_change(self, obj, attr, _, value): self.drive_filter = None if value == "All" else value self.update_data() def on_class_change(self, obj, attr, _, value): self.class_filter = None if value == "All" else value self.update_data() def update_data(self): df = mpg if self.manufacturer_filter: df = df[df["manufacturer"] == self.manufacturer_filter] if self.model_filter: df = df[df["model"] == self.model_filter] if self.transmission_filter: df = df[df["trans"] == self.transmission_filter] if self.drive_filter: df = df[df["drv"] == self.drive_filter] if self.class_filter: df = df[df["class"] == self.class_filter] self.source.data = ColumnDataSource.from_df(df) self.session.store_document(self.document) def run(self, do_view=False, poll_interval=0.5): link = self.session.object_link(self.document.context) print("Please visit %s to see the plots" % link) if do_view: view(link) print("\npress ctrl-C to exit") self.session.poll_document(self.document)
from bokeh.models.glyphs import Quad from bokeh.plotting import show N = 9 x = np.linspace(-2, 2, N) y = x**2 source = ColumnDataSource( dict( left=x, top=y, right=x - x**3 / 10 + 0.3, bottom=y - x**2 / 10 + 0.5, )) xdr = DataRange1d(sources=[source.columns("left", "right")]) ydr = DataRange1d(sources=[source.columns("top", "bottom")]) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = Quad(left="left", right="right", top="top",
from bokeh.sampledata.iris import flowers colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} flowers['color'] = flowers['species'].map(lambda x: colormap[x]) source = ColumnDataSource(data=dict(petal_length=flowers['petal_length'], petal_width=flowers['petal_width'], sepal_length=flowers['sepal_length'], sepal_width=flowers['sepal_width'], color=flowers['color'])) text_source = ColumnDataSource(data=dict(xcenter=[125], ycenter=[135])) xdr = DataRange1d(sources=[ source.columns("petal_length", "petal_width", "sepal_length", "sepal_width") ]) ydr = DataRange1d(sources=[ source.columns("petal_length", "petal_width", "sepal_length", "sepal_width") ]) 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,
source = ColumnDataSource( data=dict( petal_length=flowers['petal_length'], petal_width=flowers['petal_width'], sepal_length=flowers['sepal_length'], sepal_width=flowers['sepal_width'], color=flowers['color'] ) ) text_source = ColumnDataSource( data=dict(xcenter=[125], ycenter=[135]) ) xdr = DataRange1d(sources=[source.columns("petal_length", "petal_width", "sepal_length", "sepal_width")]) ydr = DataRange1d(sources=[source.columns("petal_length", "petal_width", "sepal_length", "sepal_width")]) 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") plot.add_glyph(source, circle) xticker = BasicTicker() if xax: xaxis = LinearAxis() plot.add_layout(xaxis, 'below')
) from bokeh.session import Session document = Document() session = Session() session.use_doc('line_animate') session.load_document(document) x = linspace(-2*pi, 2*pi, 1000) x_static = linspace(-2*pi, 2*pi, 1000) y = sin(x) z = cos(x) source = ColumnDataSource(data=dict(x=x, y=y, z=z, x_static=x_static)) xdr = DataRange1d(sources=[source.columns("x")]) xdr_static = DataRange1d(sources=[source.columns("x_static")]) ydr = DataRange1d(sources=[source.columns("y")]) plot = Plot(x_range=xdr_static, y_range=ydr, min_border=50) line_glyph = Line(x="x", y="y", line_color="blue") plot.add_glyph(source, line_glyph) line_glyph2 = Line(x="x", y="z", line_color="red") plot.add_glyph(source, line_glyph2) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') plot.add_tools(PanTool(), WheelZoomTool())
from bokeh.models.glyphs import Quad from bokeh.plotting import show N = 9 x = np.linspace(-2, 2, N) y = x**2 source = ColumnDataSource(dict( left=x, top=y, right=x-x**3/10 + 0.3, bottom=y-x**2/10 + 0.5, ) ) xdr = DataRange1d(sources=[source.columns("left", "right")]) ydr = DataRange1d(sources=[source.columns("top", "bottom")]) plot = Plot( title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = Quad(left="left", right="right", top="top", bottom="bottom", fill_color="#b3de69") plot.add_glyph(source, glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left')
ColumnDataSource, PanTool, WheelZoomTool ) from bokeh.resources import INLINE x = arange(-2 * pi, 2 * pi, 0.1) 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(sources=[source.columns("times")]) ydr = DataRange1d(sources=[source.columns("y")]) 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)
import numpy as np from bokeh.document import Document from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid from bokeh.models.markers import CircleX from bokeh.plotting import show 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)) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) plot = Plot( title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = CircleX(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')
from bokeh.models import (Plot, DataRange1d, LinearAxis, Grid, ColumnDataSource, PanTool, WheelZoomTool) from bokeh.resources import INLINE from bokeh.sampledata.iris import flowers colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} flowers['color'] = flowers['species'].map(lambda x: colormap[x]) source = ColumnDataSource(data=dict(petal_length=flowers['petal_length'], petal_width=flowers['petal_width'], sepal_length=flowers['sepal_length'], sepal_width=flowers['sepal_width'], color=flowers['color'])) xdr = DataRange1d(sources=[source.columns("petal_length")]) ydr = DataRange1d(sources=[source.columns("petal_width")]) plot = Plot(x_range=xdr, y_range=ydr, min_border=80, title="Iris Data") circle = Circle(x="petal_length", y="petal_width", size=10, fill_color="color", fill_alpha=0.2, line_color="color") plot.add_glyph(source, circle) xaxis = LinearAxis(axis_label="petal length", bounds=(1, 7), major_tick_in=0) plot.add_layout(xaxis, 'below')