def classical_gear(module, large_teeth, small_teeth): xdr = Range1d(start=-300, end=150) ydr = Range1d(start=-100, end=100) source = ColumnDataSource(data=dict(dummy=[0])) plot = Plot( title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=800 ) plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) radius = pitch_radius(module, large_teeth) angle = 0 glyph = Gear( x=-radius, y=0, module=module, teeth=large_teeth, angle=angle, fill_color=fill_color[0], line_color=line_color ) plot.add_glyph(source, glyph) radius = pitch_radius(module, small_teeth) angle = half_tooth(small_teeth) glyph = Gear( x=radius, y=0, module=module, teeth=small_teeth, angle=angle, fill_color=fill_color[1], line_color=line_color ) plot.add_glyph(source, glyph) return plot
def sample_gear(): xdr = Range1d(start=-30, end=30) ydr = Range1d(start=-30, end=30) source = ColumnDataSource(data=dict(dummy=[0])) plot = Plot(title=None, data_sources=[source], x_range=xdr, y_range=ydr, width=800, height=800) plot.tools.extend( [PanTool(plot=plot), WheelZoomTool(plot=plot), ResetTool(plot=plot)]) glyph = Gear(x=0, y=0, module=5, teeth=8, angle=0, shaft_size=0.2, fill_color=fill_color[2], line_color=line_color) renderer = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=glyph) plot.renderers.append(renderer) return plot
def sample_gear(): xdr = Range1d(start=-30, end=30) ydr = Range1d(start=-30, end=30) source = ColumnDataSource(data=dict(dummy=[0])) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=800) plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) glyph = Gear(x=0, y=0, module=5, teeth=8, angle=0, shaft_size=0.2, fill_color=fill_color[2], line_color=line_color) plot.add_glyph(source, glyph) return plot
def classical_gear(module, large_teeth, small_teeth): xdr = Range1d(start=-300, end=150) ydr = Range1d(start=-100, end=100) source = ColumnDataSource(data=dict(dummy=[0])) plot = Plot(title=None, data_sources=[source], x_range=xdr, y_range=ydr, width=800, height=800) plot.tools.extend( [PanTool(plot=plot), WheelZoomTool(plot=plot), ResetTool(plot=plot)]) radius = pitch_radius(module, large_teeth) angle = 0 glyph = Gear(x=-radius, y=0, module=module, teeth=large_teeth, angle=angle, fill_color=fill_color[0], line_color=line_color) renderer = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=glyph) plot.renderers.append(renderer) radius = pitch_radius(module, small_teeth) angle = half_tooth(small_teeth) glyph = Gear(x=radius, y=0, module=module, teeth=small_teeth, angle=angle, fill_color=fill_color[1], line_color=line_color) renderer = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=glyph) plot.renderers.append(renderer) return plot
def test_ImageRGB(self): source = _SourceShim(ar_downsample.InterpolateColor) result = ar_downsample.mapping(source) expected = { 'x_range': Range1d(start=0, end=0), 'y_range': Range1d(start=0, end=0) } self.assertEquals(len(expected), len(result)) self.assertEquals(sorted(expected.keys()), sorted(result.keys())) source = _SourceShim(ar_downsample.InterpolateColor, "A", "B", "C") result = ar_downsample.mapping(source) expected['A'] = source.defVal expected['B'] = source.defVal expected['C'] = source.defVal self.assertEquals(sorted(expected.keys()), sorted(result.keys()))
def test_span(self): self.assertEquals(0, ar_downsample._span(Range1d(start=0, end=0))) self.assertEquals(2, ar_downsample._span(Range1d(start=0, end=2))) self.assertEquals(2, ar_downsample._span(Range1d(start=-2, end=0))) self.assertEquals(4, ar_downsample._span(Range1d(start=-2, end=2))) self.assertEquals(4, ar_downsample._span(Range1d(start=2, end=-2))) self.assertEquals(3, ar_downsample._span(Range1d(start=None, end=3))) self.assertEquals(3, ar_downsample._span(Range1d(start=3, end=None))) self.assertEquals(0, ar_downsample._span(Range1d(start=None, end=None)))
def epicyclic_gear(module, sun_teeth, planet_teeth): xdr = Range1d(start=-150, end=150) ydr = Range1d(start=-150, end=150) source = ColumnDataSource(data=dict(dummy=[0])) plot = Plot( title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=800 ) plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) annulus_teeth = sun_teeth + 2*planet_teeth glyph = Gear( x=0, y=0, module=module, teeth=annulus_teeth, angle=0, fill_color=fill_color[0], line_color=line_color, internal=True ) plot.add_glyph(source, glyph) glyph = Gear( x=0, y=0, module=module, teeth=sun_teeth, angle=0, fill_color=fill_color[2], line_color=line_color ) plot.add_glyph(source, glyph) sun_radius = pitch_radius(module, sun_teeth) planet_radius = pitch_radius(module, planet_teeth) radius = sun_radius + planet_radius angle = half_tooth(planet_teeth) for i, j in [(+1, 0), (0, +1), (-1, 0), (0, -1)]: glyph = Gear( x=radius*i, y=radius*j, module=module, teeth=planet_teeth, angle=angle, fill_color=fill_color[1], line_color=line_color ) plot.add_glyph(source, glyph) return plot
def large_plot(): source = ColumnDataSource(data=dict(x=[0, 1], y=[0, 1])) xdr = Range1d(start=0, end=1) xdr.tags.append("foo") xdr.tags.append("bar") ydr = Range1d(start=10, end=20) ydr.tags.append("foo") plot = Plot(x_range=xdr, y_range=ydr) ydr2 = Range1d(start=0, end=100) plot.extra_y_ranges = {"liny": ydr2} circle = Circle(x="x", y="y", fill_color="red", size=5, line_color="black") plot.add_glyph(source, circle, name="mycircle") line = Line(x="x", y="y") plot.add_glyph(source, line, name="myline") rect = Rect(x="x", y="y", width=1, height=1, fill_color="green") plot.add_glyph(source, rect, name="myrect") plot.add_layout(DatetimeAxis(), 'below') plot.add_layout(LogAxis(), 'left') plot.add_layout(LinearAxis(y_range_name="liny"), 'left') plot.add_layout(Grid(dimension=0), 'left') plot.add_layout(Grid(dimension=1), 'left') plot.add_tools( BoxZoomTool(), PanTool(), PreviewSaveTool(), ResetTool(), ResizeTool(), WheelZoomTool(), ) return plot
def map(self, latitude=35.349, longitude=-116.595, zoom=17, load=True, title="Map"): if load: self.load_all() x_range = Range1d() y_range = Range1d() plot = GMapPlot(x_range=x_range, y_range=y_range, center_lat=latitude, center_lng=longitude, zoom_level=zoom, data_sources=[], canvas_width=600, canvas_height=600, outer_width=600, outer_height=600, title=title) select_tool = BoxSelectTool() overlay = BoxSelectionOverlay(tool=select_tool) plot.renderers.append(overlay) plot.tools.append(select_tool) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) pantool = PanTool(plot=plot) zoomtool = ZoomTool(plot=plot) plot.tools.extend([pantool, zoomtool]) self.add(plot, xgrid, ygrid, pantool, zoomtool, x_range, y_range, select_tool, overlay) self.cdx.plotlist.children.insert(0, plot) self.cdx.activeplot = plot self.cdx.plotlist._dirty = True stored = self.store_all() # print stored return stored
def plot_trip_intervals(for_lines=['4', '5', '6'], for_directions=['N', 'S']): for set_line in for_lines: db_l = db[db['line'] == set_line] for d in for_directions: db_index = db_l[db_l['direction'] == d].index.values print "referred to db index", db_index file_root = db.loc[db_index, 'file'].values[0] print file_root #D_stoptimes = pd.read_csv(file_root+"_stoptimes.csv",index_col=0) D_howlate = pd.read_csv(file_root + "_howlate.csv", index_col=0) station_order, code_order, station_map, station_index = get_station_map( d, set_line) useColor = "#0066CC" output_file("plot_trip_intervals_" + set_line + "_" + d + ".html") keepStations = [sta for sta in code_order] dropStations = [ sta for sta in D_howlate.columns if sta not in code_order ] print "dropping", dropStations D_howlate = D_howlate.drop(dropStations, axis=1) t_range = 5 figure(x_range=station_order ) #, y_range=Range1d(start=-1, end=t_range)) hold() for trip in D_howlate.index: raw_record = D_howlate.loc[trip, :] ordered_record = np.array( [raw_record[sta_code] / 60. for sta_code in code_order]) record = ordered_record[1:-1] - ordered_record[0:-2] record_jitter = [jitter(r, 0.5) for r in record] dT = pd.Series(data=record_jitter, index=code_order[1:-1]) dT = dT.dropna() late = D_howlate.loc[trip, :] useX = [ late_shift(0.1, l, 30.) + 1 + station_map[sta] for sta, l in zip(dT.index, late) ] colorList = [late_color(ll, 30.) for ll in late] #alphaList = [late_alpha(l,600.) for l in late] scatter(useX, y=dT, alpha=0.15, color=colorList) curplot().y_range = Range1d(start=0, end=10) curplot().title = "Trip Time Intervals - " + str( set_line) + " Train " + str(d) + "B" xaxis().major_label_orientation = np.pi / 4 xaxis().axis_label = "Approaching Subway Stop" yaxis().axis_label = "Trip Time (minutes)" show()
def make_object(): source = ServerDataSource(data_url="IonXpress_004_rawlib.sam", owner_username="******", transform={ 'resample': 'genomic_coverage', 'primary_column': 'coverage', 'domain_name': 'chr5' }, data={}) x_range = Range1d(start=0, end=249250621) plot1 = line('chr5', 'counts', tools="pan,wheel_zoom,box_zoom,reset,previewsave", plot_width=800, plot_height=350, source=source, x_range=x_range) plot2 = make_plot(x_range) return VBox(children=[plot1, plot2])
def get_data(username, docid, datasourceid): bokehuser = bokeh_app.authentication.current_user() request_username = bokehuser.username # handle docid later... clientdoc = bokeh_app.backbone_storage.get_document(docid) prune(clientdoc) init_bokeh(clientdoc) serverdatasource = clientdoc._models[datasourceid] parameters = json.loads(request.values.get('resample_parameters')) plot_state = json.loads(request.values.get('plot_state')) render_state = json.loads(request.values.get( 'render_state')) if 'render_state' in request.values else None # TODO: Desserializing directly to ranges....awk-ward. # There is probably a better way via the properties system that detects type...probably... plot_state = dict([(k, Range1d.load_json(r)) for k, r in iteritems(plot_state)]) result = bokeh_app.datamanager.get_data(request_username, serverdatasource, parameters, plot_state, render_state) result = make_json(protocol.serialize_json(result)) return result
def build_plot(symbol): main_plot_title = symbol data = build_data(symbol) # Generate data. file_name = '%s.html' % symbol output_file(file_name, title='How are my stocks doing today?') close = data['Close'] dates = data.index # Define plot constants. plot_width = 1000 # Perform TA on stock data. # TODO: Make the buy/sell signals actually do something. # Define SMA 50/200. sma50 = data['SMA50'] sma200 = data['SMA200'] # Define Bollinger Bands. upperband = data['Bollinger (upper)'] lowerband = data['Bollinger (lower)'] # Define RSI. rsi50 = data[ 'RSI50'] # TODO: Figure out a way to translate "crosses under/above line" to a sell signal. # Define MACD Line, Signal, and Histogram. macd = data['MACD Line'] signal = data[ 'MACD Signal'] # TODO: Actually use these. Figure out subplots! hist = data['MACD Histogram'] # Finished with the data? Then it's time to plot! x = data.index y = close # Plot RSI (remember, it goes on top) # Predefine plot for axis buggery. rsi_plot = line(x, rsi50, color='#000000', x_axis_type=None) # Define RSI axis boundaries. x_range = Range1d(start=x[0], end=x[-1]) xbounds = [x[0], x[-1]] curplot().y_range = Range1d(start=0, end=100) curplot().x_range = x_range yaxis().bounds = [0, 100] xaxis().bounds = xbounds hold() rsi_plot = line(x, rsi50, color='#000000', x_axis_type=None) line(x, (np.ones(len(rsi50)) * 30), color='#4daf4a') line(x, (np.ones(len(rsi50)) * 70), color='#e41a1c') # Miscellaneous plot attributes. rsi_plot.title = main_plot_title rsi_plot.height = 200 rsi_plot.width = plot_width rsi_plot.min_border_bottom = 10 grid().grid_line_alpha = 0.4 yaxis().axis_label = 'RSI' # Remove hold for the main plot. hold() # Plot raw stock data (main plot). main_plot = line(x, y, color='#1B9E77', legend='Price at Close', x_axis_type=None, title='') # Hold for the overlays. hold() # Plot overlays. # SMA 50: line(x, sma50, color='#D95F02', legend='50-day SMA') # SMA 200: line(x, sma200, color='#e7298a', legend='200-day SMA') # Bollinger shading glyph: bandprice = stackify( upperband, lowerband ) # Reverse the upper band data and append it to the lower band data. banddates = stackify(dates, dates) # Do the same for the dates. patch(pandas.to_datetime(banddates), bandprice, color='#7570B3', fill_alpha=0.2) # Remove hold, allow for more plots to be added. hold() # Miscellaneous plot attributes. main_plot.height = 600 main_plot.width = plot_width yaxis().axis_label = 'Price (USD)' grid().grid_line_alpha = 0.4 xaxis().bounds = xbounds curplot().x_range = x_range # Plot MACD. macd_plot = line(x, macd, color='#D95F02', title='', x_axis_type='datetime') hold() line(x, signal, color='#1B9E77') hold() # Attributes. macd_plot.height = 200 macd_plot.width = plot_width yaxis().axis_label = 'MACD' macd_plot.min_border_top = 0 macd_plot.min_border_bottom = 100 # Make a grid and snippet from this. plot_grid = gridplot([[rsi_plot], [main_plot], [macd_plot]]) snippet = plot_grid.create_html_snippet(embed_base_url='../static/js/', embed_save_loc='./static/js') # Return signal arrays. sma_signals = sma_signal(sma50, sma200) boll_signals = boll_signal(close, upperband, lowerband) rsi_signals = rsi_signal(rsi50) print '%s SMA signal says:' % symbol print sma_signals[-1] print '%s Bollinger breakout signal says:' % symbol print boll_signals[-1] print '%s RSI signal says:' % symbol print rsi_signals[-1] print "returning snippet..." return snippet
circles_source = ColumnDataSource(data=dict( xi=quartet['Ix'], yi=quartet['Iy'], xii=quartet['IIx'], yii=quartet['IIy'], xiii=quartet['IIIx'], yiii=quartet['IIIy'], xiv=quartet['IVx'], yiv=quartet['IVy'], )) x = np.linspace(-0.5, 20.5, 10) y = 3 + 0.5 * x lines_source = ColumnDataSource(data=dict(x=x, y=y)) xdr = Range1d(start=-0.5, end=20.5) ydr = Range1d(start=-0.5, end=20.5) 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')
from bokeh.objects import ( Plot, Range1d, LinearAxis, Grid, ColumnDataSource, PanTool, WheelZoomTool ) from bokeh.session import Session document = Document() session = Session() session.use_doc('prim_server') session.load_document(document) x = np.arange(1,6) y = np.arange(5, 0, -1) source = ColumnDataSource(data=dict(x=x,y=y)) xdr = Range1d(start=0, end=10) ydr = Range1d(start=0, end=10) def make_plot(name, glyph): plot = Plot(x_range=xdr, y_range=ydr, min_border=80) 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))
legend="Lituus") line(arch_x, arch_y, color="red", line_width=2, title="Archimean", legend="Archimedean") line(fermat_x, fermat_y, color="blue", line_width=2, title="Fermat", legend="Fermat") plot = curplot() plot.y_range = Range1d(start=-10, end=10) plot.x_range = Range1d(start=-10, end=10) # OK, so that doesn't look so good because Bokeh tried to autoscale to # accomodate all the data. We can use the Range1d object to set the plot range # explicitly # EXERCISE: create a new figure figure() line(golden_x, golden_y, color="black", line_width=2, title="GoldenRatio", legend="GoldenRatio",
from __future__ import print_function from math import pi, sin, cos from bokeh.document import Document from bokeh.embed import file_html from bokeh.resources import INLINE from bokeh.browserlib import view from bokeh.glyphs import Circle, Arc, Ray, Text from bokeh.objects import ColumnDataSource, Range1d, Plot, Glyph xdr = Range1d(start=-1.25, end=1.25) ydr = Range1d(start=-1.25, end=1.25) plot = Plot(title="Speedometer", data_sources=[], x_range=xdr, y_range=ydr, plot_width=600, plot_height=600) global_source = ColumnDataSource(dict(dummy=[0])) plot.data_sources.append(global_source) def add_glyph(glyph, source=global_source): renderer = Glyph(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=glyph)
theta = linspace(0, 2*pi, N) r_x = linspace(0, 6*pi, N-1) rmin = r_base - cos(r_x) - 1 rmax = r_base + sin(r_x) + 1 colors = ["FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8", "#253494", "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"] * 5 cx = cy = zeros_like(rmin) output_server("animated") hold() annular_wedge( cx, cy, rmin, rmax, theta[:-1], theta[1:], x_range = Range1d(start=-11, end=11), y_range = Range1d(start=-11, end=11), inner_radius_units="data", outer_radius_units="data", fill_color = colors, line_color="black", tools="pan,wheel_zoom,box_zoom,reset,previewsave" ) renderer = [r for r in curplot().renderers if isinstance(r, Glyph)][0] ds = renderer.data_source show() while True: for i in linspace(-2*pi, 2*pi, 50): rmin = ds.data["inner_radius"] rmin = roll(rmin, 1)
def plot_trip_trajectories(for_lines=['4', '5', '6'], for_directions=['N', 'S']): for set_line in for_lines: db_l = db[db['line'] == set_line] for d in for_directions: db_index = db_l[db_l['direction'] == d].index.values print "referred to db index", db_index file_root = db.loc[db_index, 'file'].values[0] print file_root df_stoptimes = pd.read_csv(file_root + "_stoptimes.csv", index_col=0) df_howlate = pd.read_csv(file_root + "_howlate.csv", index_col=0) station_order, code_order, station_map, station_index = get_station_map( d, set_line) first_stop = code_order[0] last_stop = code_order[-1] df_triptimes = pd.DataFrame(index=df_stoptimes.index, columns=['trip_time']) df_triptimes['trip_time'] = (df_stoptimes[last_stop] - df_stoptimes[first_stop]) / 60. useColor = "#0066CC" output_file("plot_" + set_line + "_" + d + ".html") figure(x_range=station_order) set_y_max = [] hold() dropStations = [ s for s in df_stoptimes.columns if s not in code_order ] print "Dropping anomalous stations", dropStations print[station_names[s] for s in dropStations] df_stoptimes = df_stoptimes.drop(dropStations, axis=1) df_howlate = df_howlate.drop(dropStations, axis=1) lmax = df_howlate.max().max() print "max late", lmax numPlots = 0 # generate hundreds of plots... takes a minute for trip in df_stoptimes.index: raw_record = df_stoptimes.loc[trip, :] #print col,raw_record record = pd.Series(data=[t for t in raw_record], index=df_stoptimes.columns) late = df_howlate.loc[trip, :].fillna(0) if not np.isnan(record[first_stop]): dT = (record.dropna() - record[first_stop]) / 60. if max(dT) > 0: set_y_max.append(max(dT)) useX = [1 + station_map[sta] for sta in dT.index] useX_shift = [ late_shift(0.1, 30., l) + x for x, l in zip(useX, late) ] useAlpha = [late_alpha(lll, 600.) for lll in late] colorList = [late_color(lll, 30.) for lll in late] dT = [correct_time(t) for t in dT] circle(useX_shift, y=dT, line_color=colorList, fill_color=colorList, alpha=useAlpha) line(useX, y=dT, color=useColor, alpha=0.02) numPlots += 1 print "Set y max", max(set_y_max) if max(set_y_max) > 200: use_y_max = sum(set_y_max) * 2.5 / len(set_y_max) else: use_y_max = max(set_y_max) print "Use y max", use_y_max curplot().title = "Subway Trip Trajectories - " + str( set_line) + " Train " + str(d) + "B" curplot().y_range = Range1d(start=-5, end=use_y_max + 5) xaxis().major_label_orientation = np.pi / 4 xaxis().axis_label = "Subway Stop" yaxis().axis_label = "Elapsed Time (min)" show() print "Plotted", numPlots, "trajectories"
from bokeh.embed import file_html from bokeh.glyphs import Circle from bokeh.objects import ( Plot, DataRange1d, LinearAxis, ColumnDataSource, Range1d, PanTool, WheelZoomTool ) from bokeh.resources import INLINE 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')
# EXERCISE: output static HTML file output_file("style.html") # EXERCISE: play around with parameters like: # - line_color # - line_alpha # - line_width # - line_dash (e.g., [2,4]) # - fill_color # - fill_alpha # - background_fill patches(xs, ys, x_range=categories, y_range=Range1d(start=0, end=800), color=colors, alpha=0.8, line_color="blue", line_alpha=.5, line_width=3, line_dash=[2, 3], fill_color="purple", background_fill="lightgrey", title="Categories of Brewering") # EXERCISE: configure all of the following plot properties ygrid().grid_line_color = "blue" # color, or None, to suppress the line ygrid().grid_line_width = "red" # line width for grid lines axis().major_label_text_font_size = "10pt" # "12pt", "1.5em", "10px", etc axis().major_label_text_font_style = "bold" # "bold", "normal", "italic"
def make_plot(xr): yr = Range1d(start=-10, end=10) figure(plot_width=800, plot_height=350, y_range=yr, x_range=xr, tools="xpan,xwheel_zoom,hover,box_zoom,reset") hold() genes = pd.read_csv('/home/hugoshi/data/lab7/genes.refseq.hg19.bed', sep='\t', skiprows=[0], header=None) genes.rename(columns={0: "chromosome", 1: "start", 2: "end"}, inplace=True) genes = genes[genes.chromosome == 'chr5'] g_len = len(genes) quad( genes.start - 0.5, # left edge genes.end - 0.5, # right edge [2.3] * g_len, # top edge [1.7] * g_len, ['blue'] * g_len) # bottom edge exons = pd.read_csv('/home/hugoshi/data/lab7/exons.refseq.hg19.bed', sep='\t', skiprows=[0], header=None) exons.columns = ["chromosome", "start", "end", "meta1", "meta2", "meta3"] exons = exons[exons.chromosome == 'chr5'] e_len = len(exons) quad( exons.start - 0.5, # left edge exons.end - 0.5, # right edge [1.3] * e_len, # top edge [0.7] * e_len, ['blue'] * e_len) # bottom edge df = pd.read_csv('/home/hugoshi/data/lab7/CHP2.20131001.hotspots.bed', sep='\t', skiprows=[0], header=None) df.columns = ["chromosome", "start", "end", "meta1", "meta2", "meta3"] df = df[df.chromosome == 'chr5'] singles = df[df.start + 1 == df.end] widers = df[df.start + 1 != df.end] slen = len(singles) wlen = len(widers) s_source = ColumnDataSource(data=dict(start=singles.start, end=singles.end, meta1=singles.meta1, meta2=singles.meta2, meta3=singles.meta3)) rect( 'start', # x center [1] * slen, # y center [0.9] * slen, [1] * slen, color=['red'] * slen, source=s_source) # height hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0] hover.tooltips = OrderedDict([ # add to this ("position", "@start"), ("meta 1", "@meta1"), ("meta 2", "@meta2"), ("meta 3", "@meta3") ]) quad( widers.start - 0.5, # left edge widers.end - 0.5, # right edge [0.3] * wlen, # top edge [-0.3] * wlen) # bottom edge hold() return curplot()
from bokeh.objects import (Plot, DataRange1d, Range1d, LinearAxis, Rule, ColumnDataSource, GlyphRenderer, ObjectArrayDataSource, PanTool, ZoomTool) from bokeh.glyphs import Line from bokeh import session # The Line glyph needs arrays of arrays of X and Y, so use newaxis. x = arange(-2 * pi, 2 * pi, 0.1) y = sin(x) source = ColumnDataSource(data=dict(xs=[x], ys=[y])) #xdr = DataRange1d(sources=[source.columns("xs")]) #ydr = DataRange1d(sources=[source.columns("ys")]) xdr = Range1d(start=-2 * pi, end=2 * pi) ydr = Range1d(start=-1, end=1) line = Line(xs="xs", ys="ys", line_color="blue", line_width=2) glyph_renderer = GlyphRenderer(data_source=source, xdata_range=xdr, ydata_range=ydr, glyph=line) 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) xaxis = LinearAxis(plot=plot, dimension=0) yaxis = LinearAxis(plot=plot, dimension=1) xgrid = Rule(plot=plot, dimension=0)
hold() # Next we need to actually create a new figure, so that the following # renderers work on a new plot, and not the last one. figure() # EXERCISE: add all four spirals to one plot, each with different line colors # and legend values. NOTE: title only set on the first renderer. line(golden_x, golden_y, color="#BD1550", line_width=2, legend="golden", title="Various Spirals") line(lituus_x, lituus_y, color="#E97F02", line_width=2, legend="lituus") line(arch_x, arch_y, color="#F8CA00", line_width=2, legend="Archimedean") line(fermat_x, fermat_y, color="#8A9B0F", line_width=2, legend="Fermat") # OK, so that doesn't look so good because Bokeh tried to autoscale to # accomodate all the data. We can use the Range1d object to set the plot range # explicitly # EXERCISE: create a new figure figure() # EXERCISE: add x_range and y_range parameters to the first `line`, to set the # range to [-10, 10]. NOTE: Range1d are created like: Range1d(start=0, end-10) line(golden_x, golden_y, color="#BD1550", line_width=2, legend="golden", title="Various Spirals", x_range=Range1d(start=-10, end=10), y_range=Range1d(start=-10, end=10)) line(lituus_x, lituus_y, color="#E97F02", line_width=2, legend="lituus") line(arch_x, arch_y, color="#F8CA00", line_width=2, legend="Archimedean") line(fermat_x, fermat_y, color="#8A9B0F", line_width=2, legend="Fermat") show() # show the plot
# EXERCISE: Fill in the missing parameters to use the `image` renderer to # display the Mandelbrot image 'img' with the title 'Mandelbrot', colormapped # with the palette 'Spectral-11', and a fixed range given by (min_x, max_x) # and (min_y, max_y). # # NOTE: the `image` renderer can display many images at once, so it takes # **lists** of images, coordinates, and palettes. Remember to supply sequences # for these parameters, even if you are just supply one. image( image=[img], x=[min_x], # lower left x coord y=[min_y], # lower left y coord dw=[max_x - min_x], # *data* width of image dh=[max_y - min_y], # *data* height of image palette=["Spectral-11"], # palette to colormap with x_range=Range1d(start=min_x, end=max_x), # fix the X range y_range=Range1d(start=min_y, end=max_x), # fix the Y range title="Mandelbrot", # give the plot a title tools="pan,wheel_zoom,box_zoom,reset", # add some tools plot_width=900, # set a width for the plot plot_height=600 # and a height ) # EXERCISE: create a new figure figure() # We can also use the `image_rgba` renderer to display RGBA images that # we have colormapped ourselves. N = 20 img = np.empty((N, N), dtype=np.uint32) view = img.view(dtype=np.uint8).reshape((N, N, 4))
return a * np.sqrt(np.log(mic * 1E4)) + b big_angle = 2.0 * np.pi / (len(df) + 1) small_angle = big_angle / 7 output_file("burtin.html", title="burtin.py example") hold() x = np.zeros(len(df)) y = np.zeros(len(df)) line(x+1, y+1, alpha=0, plot_width=width, plot_height=height, title="", tools="pan,wheel_zoom,box_zoom,reset,previewsave", x_axis_type=None, y_axis_type=None) plot = curplot() plot.x_range = Range1d(start=-420, end=420) plot.y_range = Range1d(start=-420, end=420) plot.min_border = 0 plot.background_fill = "#f0e1d2" plot.border_fill = "#f0e1d2" plot.outline_line_color = None # annular wedges angles = np.pi/2 - big_angle/2 - df.index*big_angle colors = [gram_color[gram] for gram in df.gram] annular_wedge( x, y, inner_radius, outer_radius, -big_angle+angles, angles, color=colors, ) # small wedges annular_wedge(
) gold = np.array([data[abbr]['gold'] for abbr in countries], dtype=np.float) silver = np.array([data[abbr]['silver'] for abbr in countries], dtype=np.float) bronze = np.array([data[abbr]['bronze'] for abbr in countries], dtype=np.float) # EXERCISE: output static HTML file output_file('olympics.html') # EXERCISE: turn on plot hold hold() # use the `rect` renderer to display stacked bars of the medal results. Note # that we set y_range explicitly on the first renderer with a `Range1d` object rect(x=countries, y=bronze/2, width=0.8, height=bronze, x_range=countries, color="#CD7F32", alpha=0.6, background_fill='#59636C', title="Olympic Medals by Country (stacked)", tools="", y_range=Range1d(start=0, end=max(gold+silver+bronze)), plot_width=800) rect(x=countries, y=bronze+silver/2, width=0.8, height=silver, x_range=countries, color="silver", alpha=0.6) # EXERCISE: add a `rect` renderer to stack the gold medal results rect(x=countries, y=bronze+silver+gold/2, width=0.8, height=gold, x_range=countries, color="gold", alpha=0.6) # EXERCISE: use grid(), axis(), etc. to style the plot. Some suggestions: # - remove the grid lines # - change the major label standoff, and major_tick_out values # - make the tick labels smaller # - set the x-axis orientation to vertical, or angled xgrid().grid_line_color = None axis().major_label_text_font_size = "8pt" axis().major_label_standoff = 0 xaxis().major_label_orientation = np.pi/3 xaxis().major_label_standoff = 6
output_server("remote_image") source = ServerDataSource(data_url="/defaultuser/array.table/array", owner_username="******", data={ 'x': [0], 'y': [0], 'global_x_range': [0, 10], 'global_y_range': [0, 10], 'global_offset_x': [0], 'global_offset_y': [0], 'dw': [10], 'dh': [10], 'palette': ["Spectral-11"] }) image(source=source, image="image", x="x", y="y", dw="dw", dh="dh", width=200, height=200, palette="palette", x_range=Range1d(start=0, end=10), y_range=Range1d(start=0, end=10), tools="pan,wheel_zoom,box_zoom,reset,previewsave") show()
import numpy as np import pandas as pd from scipy import misc import os, sys import itertools from bokeh.objects import (GMapPlot, DataRange1d, Range1d, LinearAxis, Grid, ColumnDataSource, GlyphRenderer, ObjectArrayDataSource, PanTool, ZoomTool, ResizeTool, SelectionTool, BoxSelectionOverlay) from bokeh.glyphs import MultiLine, ImageRGBA from bokeh import session x_range = Range1d() y_range = Range1d() plot = GMapPlot(x_range=x_range, y_range=y_range, center_lat=30.2861, center_lng=-97.7394, zoom_level=15, data_sources=[], canvas_width=600, canvas_height=600, outer_width=600, outer_height=600, title="Austin") select_tool = SelectionTool() overlay = BoxSelectionOverlay(tool=select_tool) plot.renderers.append(overlay) plot.tools.append(select_tool)
# EXERCISE: Fill in the missing parameters to use the `image` renderer to # display the Mandelbrot image with the title 'Mandelbrot', colormapped # with the palette 'Spectral-11', and a fixed range given by (min_x, max_x) # and (min_y, max_y). # # NOTE: the `image` renderer can display many images at once, so it takes # **lists** of images, coordinates, and palettes. Remember to supply sequences # for these parameters, even if you are just supplying one. image(image=[img], x=[min_x], y=[min_y], dw=[max_x - min_x], dh=[max_y - min_y], palette=["Spectral-11"], x_range=Range1d(start=min_x, end=max_x), y_range=Range1d(start=min_y, end=max_x), title="Mandelbrot", tools="pan,wheel_zoom,box_zoom,reset,previewsave", plot_width=900, plot_height=600) # EXERCISE: create a new figure figure() # We can also use the `image_rgba` renderer to display RGBA images that # we have colormapped ourselves. N = 20 img = np.empty((N, N), dtype=np.uint32) view = img.view(dtype=np.uint8).reshape((N, N, 4)) for i in range(N):