def make_plot(): source = ColumnDataSource( dict( dates=[date(2014, 3, i) for i in [1, 2, 3, 4, 5]], downloads=[100, 27, 54, 64, 75], )) xdr = DataRange1d(sources=[source.columns("dates")]) ydr = DataRange1d(sources=[source.columns("downloads")]) plot = Plot(title="Product downloads", x_range=xdr, y_range=ydr, plot_width=400, plot_height=400) 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 make_plot(): source = ColumnDataSource( dict( dates=[ date(2014, 3, i) for i in [1, 2, 3, 4, 5] ], downloads=[100, 27, 54, 64, 75], ) ) xdr = DataRange1d(sources=[source.columns("dates")]) ydr = DataRange1d(sources=[source.columns("downloads")]) plot = Plot(title="Product downloads", x_range=xdr, y_range=ydr, plot_width=400, plot_height=400) 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 make_plot(): source = ColumnDataSource( dict( dates=[date(2014, 3, i) for i in [1, 2, 3, 4, 5]], downloads=[100, 27, 54, 64, 75], )) xdr = DataRange1d(sources=[source.columns("dates")]) ydr = DataRange1d(sources=[source.columns("downloads")]) plot = Plot(title="Product downloads", data_sources=[source], x_range=xdr, y_range=ydr, width=400, height=400) line = Line(x="dates", y="downloads", line_color="blue") line_glyph = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=line) plot.renderers.append(line_glyph) circle = Circle(x="dates", y="downloads", fill_color="red") circle_glyph = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=circle) plot.renderers.append(circle_glyph) hover = HoverTool(plot=plot, tooltips=dict(downloads="@downloads")) plot.tools.append(hover) xaxis = DatetimeAxis(plot=plot, dimension=0) yaxis = LinearAxis(plot=plot, dimension=1) xgrid = Grid(plot=plot, dimension=0, axis=xaxis) ygrid = Grid(plot=plot, dimension=1, axis=yaxis) return plot, source
def line_advanced(): source = ColumnDataSource(data=dict(x=x,y=y,z=z,widths=widths, heights=heights)) xdr = DataRange1d(sources=[source.columns("x")]) xdr2 = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) ydr2 = DataRange1d(sources=[source.columns("y")]) line_glyph = Line(x="x", y="y", line_color="blue") renderer = GlyphRenderer(data_source = source, xdata_range = xdr, ydata_range = ydr, glyph = line_glyph) pantool = PanTool(dataranges = [xdr, ydr], dimensions=["width","height"]) zoomtool = ZoomTool(dataranges=[xdr,ydr], dimensions=("width","height")) plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], border=50) plot.tools = [pantool, zoomtool] plot.renderers.append(renderer) #notice that these two have a differen y data range renderer2 = GlyphRenderer(data_source = source, xdata_range = xdr, ydata_range = ydr2, glyph = line_glyph) plot2 = Plot(x_range=xdr, y_range=ydr2, data_sources=[source], border=50) plot2.renderers.append(renderer2) #notice that these two have a differen y data range renderer3 = GlyphRenderer(data_source = source, xdata_range = xdr2, ydata_range = ydr, glyph = line_glyph) plot3 = Plot(x_range=xdr2, y_range=ydr, data_sources=[source], border=50) plot3.renderers.append(renderer3) #this is a dummy plot with no renderers plot4 = Plot(x_range=xdr2, y_range=ydr, data_sources=[source], border=50) sess = session.HTMLFileSession("line_linked_advanced.html") sess.add(plot, renderer, source, xdr, ydr, pantool, zoomtool) sess.add(plot2, renderer2, ydr2, xdr2, renderer3, plot3, plot4) grid = GridPlot(children=[[plot, plot2], [plot3, plot4 ]], name="linked_advanced") sess.add(grid) sess.plotcontext.children.append(grid) sess.save(js="relative", css="relative", rootdir=os.path.abspath(".")) print "Wrote line_linked_advanced.html" webbrowser.open("file://" + os.path.abspath("line_linked_advanced.html"))
def large_plot(n): from bokeh.objects import (Plot, PlotContext, LinearAxis, Grid, Glyph, ColumnDataSource, DataRange1d, PanTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, BoxSelectionOverlay, ResizeTool, PreviewSaveTool, ResetTool) from bokeh.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, data_sources=[source]) xaxis = LinearAxis(plot=plot, dimension=0) yaxis = LinearAxis(plot=plot, dimension=1) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) renderer = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=Line(x='x', y='y')) plot.renderers.append(renderer) pan = PanTool(plot=plot, dataranges=[xdr, ydr]) wheel_zoom = WheelZoomTool(plot=plot, dataranges=[xdr, ydr]) box_zoom = BoxZoomTool(plot=plot) box_select = BoxSelectTool(plot=plot) box_selection = BoxSelectionOverlay(tool=box_select) resize = ResizeTool(plot=plot) previewsave = PreviewSaveTool(plot=plot, dataranges=[xdr, ydr]) 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] + 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=dict(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 make_plot(): from numpy import pi, arange, sin, cos import numpy as np from bokeh.objects import ( Plot, DataRange1d, LinearAxis, ColumnDataSource, GlyphRenderer, PanTool, PreviewSaveTool) from bokeh.glyphs import Circle from bokeh import session x = arange(-2*pi, 2*pi, 0.1) y = sin(x) z = cos(x) widths = np.ones_like(x) * 0.02 heights = np.ones_like(x) * 0.2 source = ColumnDataSource(data=dict(x=x,y=y,z=z,widths=widths, heights=heights)) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) circle = Circle(x="x", y="y", fill="red", radius=5, line_color="black") glyph_renderer = GlyphRenderer( data_source = source, xdata_range = xdr, ydata_range = ydr, glyph = circle) pantool = PanTool(dataranges = [xdr, ydr], dimensions=["width","height"]) previewtool = PreviewSaveTool(dataranges=[xdr,ydr], dimensions=("width","height")) plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], border= 80) xaxis = LinearAxis(plot=plot, dimension=0) yaxis = LinearAxis(plot=plot, dimension=1) plot.renderers.append(glyph_renderer) plot.tools = [pantool, previewtool] sess = session.PlotServerSession( username="******", serverloc="http://localhost:5006", userapikey="nokey") sess.use_doc("glyph2") sess.add(plot, glyph_renderer, xaxis, yaxis, # xgrid, ygrid, source, xdr, ydr, pantool, previewtool) sess.plotcontext.children.append(plot) sess.plotcontext._dirty = True # not so nice.. but set the model doens't know # that we appended to children sess.store_all() return plot
def make_plot(): source = ColumnDataSource(dict( dates = [ date(2014, 3, i) for i in [1, 2, 3, 4, 5] ], downloads = [100, 27, 54, 64, 75], )) xdr = DataRange1d(sources=[source.columns("dates")]) ydr = DataRange1d(sources=[source.columns("downloads")]) plot = Plot(title="Product downloads", data_sources=[source], x_range=xdr, y_range=ydr, width=400, height=400) line = Line(x="dates", y="downloads", line_color="blue") line_glyph = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=line) plot.renderers.append(line_glyph) circle = Circle(x="dates", y="downloads", fill_color="red") circle_glyph = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=circle) plot.renderers.append(circle_glyph) hover = HoverTool(plot=plot, tooltips=dict(downloads="@downloads")) plot.tools.append(hover) xaxis = DatetimeAxis(plot=plot, dimension=0) yaxis = LinearAxis(plot=plot, dimension=1) xgrid = Grid(plot=plot, dimension=0, axis=xaxis) ygrid = Grid(plot=plot, dimension=1, axis=yaxis) return plot, source
def make_box_violin_plot(data, num_bins, maxwidth=0.9): """ data: dict[Str -> List[Number]] maxwidth: float Maximum width of tornado plot within each factor/facet Returns the plot object """ df = pd.DataFrame(columns=["group", "centers", "width", "height", "texts"]) bar_height = 50 bins = [0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6] # Compute histograms, while keeping track of max Y values and max counts for i, (group, vals) in enumerate(data.iteritems()): hist, edges = np.histogram(vals, bins) df = df.append(pd.DataFrame(dict( group = group, centers = np.arange(len(hist))*bar_height, width = np.log10(hist), height = np.ones(hist.shape)*bar_height, texts = map(str,hist), ))) df.replace(-np.inf, 0) # Normalize the widths df["width"] *= (maxwidth / df["width"].max()) ds = ColumnDataSource(df) xdr = FactorRange(factors=sorted(df["group"].unique())) ydr = DataRange1d(sources=[ds.columns("centers")]) plot = Plot(data_sources=[ds], x_range=xdr, y_range=ydr, title="Degree Distribution", plot_width=750, plot_height=600, tools=[]) xaxis = CategoricalAxis(plot=plot, location="bottom", axis_label="number of nodes") #yaxis = LogAxis(plot=plot, location="left", axis_label="degree") plot.below.append(xaxis) #plot.above.append(yaxis) #xgrid = Grid(plot=plot, dimension=0, axis=xaxis) #ygrid = Grid(plot=plot, dimension=1, axis=yaxis) glyph = Rect(x="group", y="centers", width="width", height="height") text_glyph = Text(x="group", y="centers", text="texts", text_baseline="middle", text_align="center") plot.renderers.append(Glyph(data_source=ds, xdata_range=xdr, ydata_range=ydr, glyph=glyph)) plot.renderers.append(Glyph(data_source=ds, xdata_range=xdr, ydata_range=ydr, glyph=text_glyph)) return plot
def large_plot(n): from bokeh.objects import (Plot, PlotContext, LinearAxis, Grid, Glyph, ColumnDataSource, DataRange1d, PanTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, BoxSelectionOverlay, ResizeTool, PreviewSaveTool, ResetTool) from bokeh.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, data_sources=[source]) xaxis = LinearAxis(plot=plot, dimension=0) yaxis = LinearAxis(plot=plot, dimension=1) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) tickers = [ xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter ] renderer = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=Line(x='x', y='y')) 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] + tickers + tools) return context, objects
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
z = (cos(x) + 1) * 6 + 6 widths = np.ones_like(x) * 0.02 heights = np.ones_like(x) * 0.2 source = ColumnDataSource( data=dict(x=x, y=y, z=z, widths=widths, heights=heights)) #source = ObjectArrayDataSource( # data = [ # {'x' : 1, 'y' : 5, 'z':3}, # {'x' : 2, 'y' : 4, 'z':3, 'radius':10}, # {'x' : 3, 'y' : 3, 'z':3, 'fill':"blue"}, # {'x' : 4, 'y' : 2, 'z':3}, # {'x' : 5, 'y' : 1, 'z':3}, # ]) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) circle = Circle(x="x", y="y", fill_color="red", radius="z", line_color="black") glyph_renderer = GlyphRenderer( data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=circle, ) pantool = PanTool(dataranges=[xdr, ydr], dimensions=["width", "height"]) zoomtool = ZoomTool(dataranges=[xdr, ydr], dimensions=("width", "height")) plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], border=80)
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")]) county_patches = Patches(xs="county_xs", ys="county_ys", fill_color="county_colors", fill_alpha=0.7, line_color="white", line_width=0.5) state_patches = Patches(xs="state_xs", ys="state_ys", fill_alpha=0.0, line_color="#884444", line_width=2) county_renderer = Glyph( data_source = county_source, xdata_range = xdr, ydata_range = ydr, glyph = county_patches, ) state_renderer = Glyph( data_source = state_source, xdata_range = xdr,
from bokeh.objects import (Plot, DataRange1d, LinearAxis, DatetimeAxis, ColumnDataSource, GlyphRenderer, PanTool, ZoomTool) from bokeh.glyphs import Circle from bokeh import session 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")]) circle = Circle(x="times", y="y", fill_color="red", radius=5, line_color="black") glyph_renderer = GlyphRenderer( data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=circle, ) plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], border=80) xaxis = DatetimeAxis(plot=plot, dimension=0, location="min") yaxis = LinearAxis(plot=plot, dimension=1, location="min")
class Population(object): year = 2010 location = "World" def __init__(self): from bokeh.objects 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') self.session.load_document(self.document) self.df = load_population() self.source_pyramid = ColumnDataSource(data=dict()) def render(self): self.pyramid_plot() self.create_layout() self.document.add(self.layout) self.update_pyramid() def pyramid_plot(self): from bokeh.objects import (Plot, DataRange1d, LinearAxis, Grid, Legend, SingleIntervalTicker) from bokeh.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=None, 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.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(children=[year_select, location_select]) self.layout = VBox(children=[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)
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", header="Manufacturer", type="autocomplete", source=manufacturers), TableColumn(field="model", header="Model", type="autocomplete", source=models), TableColumn(field="displ", header="Displacement", type="numeric", format="0.00"), TableColumn(field="year", header="Year", type="numeric"), TableColumn(field="cyl", header="Cylinders", type="numeric"), TableColumn(field="trans", header="Transmission", type="dropdown", strict=True, source=transmissions), TableColumn(field="drv", header="Drive", type="autocomplete", strict=True, source=drives), TableColumn(field="class", header="Class", type="autocomplete", strict=True, source=classes), TableColumn(field="cty", header="City MPG", type="numeric"), TableColumn(field="hwy", header="Highway MPG", type="numeric"), ] handson_table = HandsonTable(source=self.source, columns=columns, sorting=True) xdr = DataRange1d(sources=[self.source.columns("index")]) #xdr = FactorRange(factors=manufacturers) ydr = DataRange1d(sources=[self.source.columns("cty"), self.source.columns("hwy")]) plot = Plot(title=None, data_sources=[self.source], 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(data_source=self.source, glyph=Circle(x="index", y="cty", fill_color="green")) hwy = Glyph(data_source=self.source, glyph=Circle(x="index", y="hwy", fill_color="red")) select_tool = BoxSelectTool(renderers=[cty, hwy], select_y=False) plot.tools.append(select_tool) overlay = BoxSelectionOverlay(tool=select_tool) plot.renderers.extend([cty, hwy, ygrid, overlay]) 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, handson_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, poll_interval=0.5): link = self.session.object_link(self.document.context) print("Please visit %s to see the plots (press ctrl-C to exit)" % link) try: while True: self.session.load_document(self.document) time.sleep(poll_interval) except KeyboardInterrupt: print() except ConnectionError: print("Connection to bokeh-server was terminated")
class Population(object): year = 2010 location = "World" def __init__(self): from bokeh.objects 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()) def render(self): self.pyramid_plot() self.create_layout() self.document.add(self.layout) self.update_pyramid() def pyramid_plot(self): from bokeh.objects import (Plot, DataRange1d, LinearAxis, Grid, Glyph, Legend, SingleIntervalTicker) from bokeh.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(plot=self.plot) self.plot.below.append(xaxis) yaxis = LinearAxis(plot=self.plot, ticker=SingleIntervalTicker(interval=5)) self.plot.left.append(yaxis) xgrid = Grid(plot=self.plot, dimension=0, ticker=xaxis.ticker) ygrid = Grid(plot=self.plot, dimension=1, ticker=yaxis.ticker) male_quad = Quad(left="male", right=0, bottom="groups", top="shifted", fill_color="blue") male_quad_glyph = Glyph(data_source=self.source_pyramid, xdata_range=xdr, ydata_range=ydr, glyph=male_quad) self.plot.renderers.append(male_quad_glyph) female_quad = Quad(left=0, right="female", bottom="groups", top="shifted", fill_color="violet") female_quad_glyph = Glyph(data_source=self.source_pyramid, xdata_range=xdr, ydata_range=ydr, glyph=female_quad) self.plot.renderers.append(female_quad_glyph) legend = Legend(plot=self.plot, legends=dict(Male=[male_quad_glyph], Female=[female_quad_glyph])) self.plot.renderers.append(legend) 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.widgetobjects 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(children=[year_select, location_select]) self.layout = VBox(children=[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)
def generate_embed_test(): """this generates a new plot and uses the script inject to put it into a page running this repeatedly will fill up your redis DB quickly, but it allows quick iteration """ from numpy import pi, arange, sin, cos import numpy as np from bokeh.objects import ( Plot, DataRange1d, LinearAxis, Rule, ColumnDataSource, GlyphRenderer, PanTool, ZoomTool, PreviewSaveTool) from bokeh.glyphs import Circle from bokeh import session x = arange(-2*pi, 2*pi, 0.1) y = sin(x) z = cos(x) widths = np.ones_like(x) * 0.02 heights = np.ones_like(x) * 0.2 source = ColumnDataSource(data=dict(x=x,y=y,z=z,widths=widths, heights=heights)) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) circle = Circle(x="x", y="y", fill="red", radius=5, line_color="black") glyph_renderer = GlyphRenderer( data_source = source, xdata_range = xdr, ydata_range = ydr, glyph = circle) pantool = PanTool(dataranges = [xdr, ydr], dimensions=["width","height"]) #zoomtool = ZoomTool(dataranges=[xdr,ydr], dimensions=("width","height")) previewtool = PreviewSaveTool(dataranges=[xdr,ydr], dimensions=("width","height")) plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], border= 80) xaxis = LinearAxis(plot=plot, dimension=0) yaxis = LinearAxis(plot=plot, dimension=1) xgrid = Rule(plot=plot, dimension=0) ygrid = Rule(plot=plot, dimension=1) plot.renderers.append(glyph_renderer) plot.tools = [pantool, previewtool] sess = session.PlotServerSession( username="******", serverloc="http://localhost:5006", userapikey="nokey") sess.use_doc("glyph2") sess.add(plot, glyph_renderer, xaxis, yaxis, xgrid, ygrid, source, xdr, ydr, pantool, previewtool) sess.plotcontext.children.append(plot) sess.plotcontext._dirty = True # not so nice.. but set the model doens't know # that we appended to children sess.store_all() if app.debug: slug = hemlib.slug_json() static_js = hemlib.slug_libs(app, slug['libs']) hemsource = os.path.join(app.static_folder, "coffee") hem_js = hemlib.coffee_assets(hemsource, "localhost", 9294) hemsource = os.path.join(app.static_folder, "vendor", "bokehjs", "coffee") hem_js += hemlib.coffee_assets(hemsource, "localhost", 9294) else: static_js = ['/bokeh/static/js/application.js'] hem_js = [] return render_template("generate_embed_test.html", jsfiles=static_js, hemfiles=hem_js, plot_scr=plot.script_inject())
GlyphRenderer, ObjectArrayDataSource, PanTool, ZoomTool) from bokeh.glyphs import Circle from bokeh import session 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")]) circle = Circle(x="petal_length", y="petal_width", fill_color="color", fill_alpha=0.2, radius=5, line_color="color") glyph_renderer = GlyphRenderer( data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=circle, )
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, data_sources=[source, patch1_source, patch2_source, text_source], 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) patch1_glyph = Glyph(data_source=patch1_source, xdata_range=xdr, ydata_range=ydr, glyph=patch1) plot.renderers.append(patch1_glyph) patch2 = Patch(x="dates", y="times", fill_color="orange", fill_alpha=0.8) patch2_glyph = Glyph(data_source=patch2_source, xdata_range=xdr, ydata_range=ydr, glyph=patch2) plot.renderers.append(patch2_glyph) line1 = Line(x="dates", y="sunrises", line_color="yellow", line_width=2) line1_glyph = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=line1)
def make_plot(): from numpy import pi, arange, sin, cos import numpy as np from bokeh.objects import (Plot, DataRange1d, LinearAxis, ColumnDataSource, GlyphRenderer, PanTool, PreviewSaveTool) from bokeh.glyphs import Circle from bokeh import session x = arange(-2 * pi, 2 * pi, 0.1) y = sin(x) z = cos(x) widths = np.ones_like(x) * 0.02 heights = np.ones_like(x) * 0.2 source = ColumnDataSource( data=dict(x=x, y=y, z=z, widths=widths, heights=heights)) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) circle = Circle(x="x", y="y", fill="red", radius=5, line_color="black") glyph_renderer = GlyphRenderer(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=circle) pantool = PanTool(dataranges=[xdr, ydr], dimensions=["width", "height"]) previewtool = PreviewSaveTool(dataranges=[xdr, ydr], dimensions=("width", "height")) plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], border=80) xaxis = LinearAxis(plot=plot, dimension=0) yaxis = LinearAxis(plot=plot, dimension=1) plot.renderers.append(glyph_renderer) plot.tools = [pantool, previewtool] sess = session.PlotServerSession(username="******", serverloc="http://localhost:5006", userapikey="nokey") sess.use_doc("glyph2") sess.add( plot, glyph_renderer, xaxis, yaxis, # xgrid, ygrid, source, xdr, ydr, pantool, previewtool) sess.plotcontext.children.append(plot) sess.plotcontext._dirty = True # not so nice.. but set the model doens't know # that we appended to children sess.store_all() return plot
widths = np.ones_like(x) * 0.02 heights = np.ones_like(x) * 0.2 source = ColumnDataSource(data=dict(x=x,y=y,z=z,widths=widths, heights=heights)) #source = ObjectArrayDataSource( # data = [ # {'x' : 1, 'y' : 5, 'z':3}, # {'x' : 2, 'y' : 4, 'z':3, 'radius':10}, # {'x' : 3, 'y' : 3, 'z':3, 'fill':"blue"}, # {'x' : 4, 'y' : 2, 'z':3}, # {'x' : 5, 'y' : 1, 'z':3}, # ]) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) circle = Circle(x="x", y="y", fill="red", radius="z", line_color="black") glyph_renderer = GlyphRenderer( data_source = source, xdata_range = xdr, ydata_range = ydr, glyph = circle, ) pantool = PanTool(dataranges = [xdr, ydr], dimensions=["width","height"]) zoomtool = ZoomTool(dataranges=[xdr,ydr], dimensions=("width","height"))
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")]) circle = Circle(x="petal_length", y="petal_width", fill_color="color", fill_alpha=0.2, size=10, line_color="color") glyph_renderer = Glyph( data_source = source, xdata_range = xdr, ydata_range = ydr, glyph = circle, ) plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], min_border=80, title="Iris Data") xaxis = LinearAxis(plot=plot, dimension=0, location="min", axis_label="petal length", bounds=(1,7), major_tick_in=0) yaxis = LinearAxis(plot=plot, dimension=1, location="min",
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, data_sources=[source, patch1_source, patch2_source, text_source], x_range=xdr, y_range=ydr, width=800, height=400) patch1 = Patch(x="dates", y="times", fill_color="skyblue", fill_alpha=0.8) patch1_glyph = Glyph(data_source=patch1_source, xdata_range=xdr, ydata_range=ydr, glyph=patch1)
from bokeh.objects import (Plot, DataRange1d, LinearAxis, DatetimeAxis, ColumnDataSource, Glyph, PanTool, WheelZoomTool) from bokeh.glyphs import Circle from bokeh import session 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")]) circle = Circle(x="times", y="y", fill_color="red", size=5, line_color="black") glyph_renderer = Glyph( data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=circle, ) plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], border=80) xaxis = DatetimeAxis(plot=plot, dimension=0, location="min") yaxis = LinearAxis(plot=plot, dimension=1, location="min")
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,
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=[145]) ) 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")]) pan = PanTool(dataranges=[xdr,ydr], dimensions=["x","y"]) zoom = WheelZoomTool(dataranges=[xdr,ydr], dimensions=["x","y"]) def make_plot(xname, yname, xax=False, yax=False, text=None): plot = Plot( x_range=xdr, y_range=ydr, data_sources=[source], background_fill="#ffeedd", width=250, height=250, border_fill='white', title="", border_symmetry="", min_border=2) if xax: xaxis = LinearAxis(plot=plot, dimension=0, location="bottom") if yax: yaxis = LinearAxis(plot=plot, dimension=1, location="left") xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1)
from bokeh import session 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(center=[125])) 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") ]) pan = PanTool(dataranges=[xdr, ydr], dimensions=["x", "y"]) zoom = ZoomTool(dataranges=[xdr, ydr], dimensions=["x", "y"]) def make_plot(xname, yname, xax=False, yax=False, text=None): plot = Plot(x_range=xdr, y_range=ydr, data_sources=[source], background_fill="#ffeedd",
def iris_splom(): 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(center=[125]) ) 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")]) pan = PanTool(dataranges=[xdr,ydr], dimensions=["x","y"]) zoom = ZoomTool(dataranges=[xdr,ydr], dimensions=["x","y"]) def make_plot(xname, yname, xax=False, yax=False, text=None): plot = Plot( x_range=xdr, y_range=ydr, data_sources=[source], background_fill="#ffeedd", width=250, height=250, border_fill='white', title="", border_symmetry="", min_border=2) objs = [] if xax: xaxis = LinearAxis(plot=plot, dimension=0, location="bottom") objs.append(xaxis) if yax: yaxis = LinearAxis(plot=plot, dimension=1, location="left") objs.append(yaxis) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) circle = Circle(x=xname, y=yname, fill_color="color", fill_alpha=0.2, radius=2, line_color="color") circle_renderer = GlyphRenderer( data_source = source, xdata_range = xdr, ydata_range = ydr, glyph = circle, ) plot.renderers.append(circle_renderer) plot.tools = [pan, zoom] if text: text = " ".join(text.split('_')) text = Text( x={'field':'center', 'units':'screen'}, y={'field':'center', 'units':'screen'}, text=text, angle=pi/4, text_font_style="bold", text_baseline="top", text_color="#ffaaaa", text_alpha=0.5, text_align="center", text_font_size="28pt") text_renderer = GlyphRenderer( data_source=text_source, xdata_range = xdr, ydata_range = ydr, glyph = text, ) plot.data_sources.append(text_source) plot.renderers.append(text_renderer) objs.append(text_renderer) objs.append(text_source) return plot, objs + [circle_renderer, xgrid, ygrid] sess = session.HTMLFileSession("iris_splom.html") attrs = ["petal_length", "petal_width", "sepal_width", "sepal_length"] plots = [] for y in attrs: row = [] for x in attrs: xax = (y == attrs[-1]) yax = (x == attrs[0]) text = x if (x==y) else None plot, objs = make_plot(x, y, xax, yax, text) sess.add(plot, *objs) row.append(plot) plots.append(row) grid = GridPlot(children=plots, name="iris_splom") sess.add(source, xdr, ydr, pan, zoom) sess.add(grid) sess.plotcontext.children.append(grid) sess.save(js="relative", css="relative", rootdir=os.path.abspath(".")) return grid
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", header="Manufacturer", type="autocomplete", source=manufacturers), TableColumn(field="model", header="Model", type="autocomplete", source=models), TableColumn(field="displ", header="Displacement", type="numeric", format="0.00"), TableColumn(field="year", header="Year", type="numeric"), TableColumn(field="cyl", header="Cylinders", type="numeric"), TableColumn(field="trans", header="Transmission", type="dropdown", strict=True, source=transmissions), TableColumn(field="drv", header="Drive", type="autocomplete", strict=True, source=drives), TableColumn(field="class", header="Class", type="autocomplete", strict=True, source=classes), TableColumn(field="cty", header="City MPG", type="numeric"), TableColumn(field="hwy", header="Highway MPG", type="numeric"), ] handson_table = HandsonTable(source=self.source, columns=columns, sorting=True) xdr = DataRange1d(sources=[self.source.columns("index")]) #xdr = FactorRange(factors=manufacturers) ydr = DataRange1d( sources=[self.source.columns("cty"), self.source.columns("hwy")]) plot = Plot(title=None, data_sources=[self.source], 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(data_source=self.source, glyph=Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5)) hwy = Glyph(data_source=self.source, glyph=Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5)) select_tool = BoxSelectTool(renderers=[cty, hwy], select_y=False) plot.tools.append(select_tool) overlay = BoxSelectionOverlay(tool=select_tool) plot.renderers.extend([cty, hwy, ygrid, overlay]) 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, handson_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 import session from bokeh import document document = document.Document() session = session.Session() session.use_doc('line_animate') session.load_document(document) x = np.linspace(-2 * pi, 2 * pi, 1000) x_static = np.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")]) line_glyph = Line(x="x", y="y", line_color="blue") line_glyph2 = Line(x="x", y="z", line_color="red") renderer = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=line_glyph) renderer2 = Glyph(data_source=source, xdata_range=xdr_static, ydata_range=ydr, glyph=line_glyph2) plot = Plot(x_range=xdr_static,
PanTool, ZoomTool) from bokeh.glyphs import Line from bokeh import session x = np.linspace(-2*pi, 2*pi, 1000) x_static = np.linspace(-2*pi, 2*pi, 1000) y = sin(x) z = cos(x) widths = np.ones_like(x) * 0.02 heights = np.ones_like(x) * 0.2 source = ColumnDataSource( data=dict(x=x, y=y, z=z, x_static=x_static, widths=widths, heights=heights)) xdr = DataRange1d(sources=[source.columns("x")]) xdr_static = DataRange1d(sources=[source.columns("x_static")]) ydr = DataRange1d(sources=[source.columns("y")]) line_glyph = Line(x="x", y="y", line_color="blue") line_glyph2 = Line(x="x", y="z", line_color="red") renderer = Glyph( data_source = source, xdata_range = xdr, ydata_range = ydr, glyph = line_glyph ) renderer2 = Glyph( data_source = source, xdata_range = xdr_static, ydata_range = ydr,
def make_box_violin_plot(data, num_bins, maxwidth=0.9): """ data: dict[Str -> List[Number]] maxwidth: float Maximum width of tornado plot within each factor/facet Returns the plot object """ df = pd.DataFrame(columns=["group", "centers", "width", "height", "texts"]) bar_height = 50 bins = [0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6] # Compute histograms, while keeping track of max Y values and max counts for i, (group, vals) in enumerate(data.iteritems()): hist, edges = np.histogram(vals, bins) df = df.append( pd.DataFrame( dict( group=group, centers=np.arange(len(hist)) * bar_height, width=np.log10(hist), height=np.ones(hist.shape) * bar_height, texts=map(str, hist), ))) df.replace(-np.inf, 0) # Normalize the widths df["width"] *= (maxwidth / df["width"].max()) ds = ColumnDataSource(df) xdr = FactorRange(factors=sorted(df["group"].unique())) ydr = DataRange1d(sources=[ds.columns("centers")]) plot = Plot(data_sources=[ds], x_range=xdr, y_range=ydr, title="Degree Distribution", plot_width=750, plot_height=600, tools=[]) xaxis = CategoricalAxis(plot=plot, location="bottom", axis_label="number of nodes") #yaxis = LogAxis(plot=plot, location="left", axis_label="degree") plot.below.append(xaxis) #plot.above.append(yaxis) #xgrid = Grid(plot=plot, dimension=0, axis=xaxis) #ygrid = Grid(plot=plot, dimension=1, axis=yaxis) glyph = Rect(x="group", y="centers", width="width", height="height") text_glyph = Text(x="group", y="centers", text="texts", text_baseline="middle", text_align="center") plot.renderers.append( Glyph(data_source=ds, xdata_range=xdr, ydata_range=ydr, glyph=glyph)) plot.renderers.append( Glyph(data_source=ds, xdata_range=xdr, ydata_range=ydr, glyph=text_glyph)) return plot