def __init__(self, root, scaled = True, nodelabels = True, tiplabels = True, showplot = True, hover = False): """ BokehTree class for plotting trees Args: root (Node): A node object. scaled (bool): Whether or not the tree is scaled. Optional, defaults to True nodelabels (bool): Whether or not to show node labels. Optional, defaults to True. tiplabels (bool): Whether or not to show tip labels. Optional, defaults to True. showplot(bool): Whether or not to display when drawtree is called. Optional, defaults to True. hover (bool): Whether or not to use the hover tool. Optional, defaults to false. """ self.root = root self.n2c = None self.xoff = 0 self.yoff = 0 self.coords = None # Plot coordinates for each node self.tools = [WheelZoomTool(),BoxZoomTool(),ResizeTool(), ResetTool(),PanTool(),PreviewSaveTool()] self.source = None # Data source for plotting node points. self.nodelabels = nodelabels self.tiplabels = tiplabels self.showplot = showplot self.scaled = scaled self.hover = hover
def get_ceil_plot(time_int=None, t_min=None, t_max=None): if time_int == None: time_int = cs.time_int plot_height = cs.plot_height plot_width = cs.plot_width border_left = cs.border_left if t_min == None or t_max == None: t_max, t_min = get_first_time_interval() t_span = t_max - t_min data = sql_con.get_data_bs(time_int=time_int, t_min=t_min, t_max=t_max) # print data ll = len(data) toolset = [CrosshairTool(), WheelZoomTool(), PreviewSaveTool(), PanTool()] plot = figure(x_range=DataRange1d(start=(t_min - t_span * .1) * 1000, end=(t_max + t_span * .1) * 1000), y_range=[0, 250 * 15], plot_height=plot_height, plot_width=plot_width, x_axis_type="datetime", min_border_left=border_left, toolbar_location="right", tools=toolset) plot.yaxis.axis_label = "meters above ground" dd = [] tt = [] y = [] dw = [] dh = [] for i in range(ll): dd.append(data.iloc[i:i + 1, 1:].T.values) tt.append(int(data.iloc[i, 0]) * 1000 - time_int * 1000 / 2) y.append(0) dw.append(time_int * 1000) dh.append(250 * 15) plot.image(image=dd, x=tt, y=y, dw=dw, dh=dh, palette="Spectral11", dilate=True) plot.title = cs.plot_title_ceil + ' averaged to {} seconds'.format( time_int) return plot
def get_weather_plot(time_int=None, t_min=None, t_max=None): plot_height = cs.plot_height plot_width = cs.plot_width border_left = cs.border_left column_names = cs.column_names_weewx column_time = cs.time_column_name_weewx if t_max == None or t_min == None: t_max, t_min = get_first_time_interval() t_span = t_max - t_min if time_int == None: time_int = cs.time_int data_seconds = sql_con.get_data_ws(time_int=time_int, t_min=t_min, t_max=t_max) data_seconds.iloc[:, 0] = data_seconds.iloc[:, 0] * 1000 plot = Plot( x_range=DataRange1d(start=(t_min - t_span * .1) * 1000, end=(t_max + t_span * .1) * 1000), y_range=DataRange1d(), plot_width=plot_width, plot_height=plot_height, # x_axis_type="datetime", min_border_left=border_left, toolbar_location="right") add_glyphs_to_plot(column_names, column_time, data_seconds, plot, 'source_weather') plot.add_layout(DatetimeAxis(name="date_time_axis"), 'below') plot.add_tools( PanTool(), WheelZoomTool(), # ResizeTool(), CrosshairTool(), PreviewSaveTool()) Grid(plot=plot, dimension=0, ticker=plot.select('date_time_axis')[0].ticker) Grid(plot=plot, dimension=1, ticker=plot.select(type=LinearAxis, name=column_names[0])[0].ticker) set_legends(plot) plot.title = cs.plot_title_weewx + ' averaged to {} seconds'.format( time_int) return plot
def large_plot(n): from bokeh.models import (Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, BoxSelectionOverlay, ResizeTool, PreviewSaveTool, ResetTool) from bokeh.models.widgets.layouts import VBox from bokeh.models.glyphs import Line vbox = VBox() objects = set([vbox]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis(plot=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) plot.renderers.append(box_selection) resize = ResizeTool(plot=plot) previewsave = PreviewSaveTool(plot=plot) reset = ResetTool(plot=plot) tools = [ pan, wheel_zoom, box_zoom, box_select, resize, previewsave, reset ] plot.tools.extend(tools) vbox.children.append(plot) objects |= set([ source, xdr, ydr, plot, xaxis, yaxis, xgrid, ygrid, renderer, glyph, plot.tool_events, box_selection ] + tickers + tools) return vbox, objects
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 plt(Title, dependentTitle, dependent): Source = ColumnDataSource(data=dict( i=mergedDF.Borough, x=mergedDF.RateOfAcuteSTIsPer1000Population, y=dependent, z=mergedDF.TotalMedianAnnualHouseholdIncomeEstimateFor2013, )) hover = HoverTool( tooltips=[("Borough", "@i"), ("Rate Of Acute STIs Per 1000 Population", "$x"), (dependentTitle, "$y"), ("Total Median Annual Household Income Estimate For 2013", "@z")]) colorColumn = [] for i in range(len(mergedDF)): #if mergedDF["out_sti"][i] == 1 and mergedDF["out_preg"][i] != 1: if i in outMD: colorColumn.append("grey") else: colorColumn.append("teal") TOOLS = [ BoxSelectTool(), WheelZoomTool(), ResetTool(), BoxSelectTool(), PreviewSaveTool(), hover ] p = figure(title=Title, tools=TOOLS) p.xaxis.axis_label = 'Rate Of Acute STIs Per 1000 Population' p.xaxis.axis_label_text_font_size = "12pt" p.yaxis.axis_label = dependentTitle p.yaxis.axis_label_text_font_size = "12pt" p.inverted_triangle(mergedDF.RateOfAcuteSTIsPer1000Population, dependent, color=colorColumn, size=15, alpha=0.5, source=Source) return p
# Add start tick source = ColumnDataSource(dict(x=[0, 0], y=[track_inner_radius, track_outer_radius])) line = Line(x='x', y='y', line_color="black", line_width=2) plot.add_glyph(source, line) # Add tooltip features_tooltip = [ ("Start base", "@start_location"), ("End base", "@end_location"), ("Type", "@type"), ("Locus tag", "@locus_tag"), ("Strand", "@strand") ] # Set renderers=[features] so that the tooltip appears only for Annular Wedge glpyhs features_hovertool = HoverTool(renderers=[features], tooltips=features_tooltip, point_policy='follow_mouse') #Add tools to the plot; create a document; add the plot to it plot.add_tools(WheelZoomTool(), PreviewSaveTool(), ResetTool(), HelpTool(), PanTool(), features_hovertool) doc = Document() doc.add(plot) if __name__ == "__main__": filename = "test.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "test")) print("Wrote %s" % filename) view(filename)
y_range=y_range, map_options=map_options, title="Map") source = ColumnDataSource( data=dict(i=uni.INSTNM, x=uni.LONGITUDE, y=uni.LATITUDE, z=uni.TUITFTE)) hover = HoverTool(tooltips=[("Institution", "@i"), ("Lon", "$x"), ( "Lat", "$y"), ("Net tuition revenue per full-time equivalent student", "@z")]) box_select = BoxSelectTool() TOOLS = [ box_select, WheelZoomTool(), ResetTool(), PreviewSaveTool(), hover, PanTool() ] circle = Circle(x='x', y='y', size=7, fill_color='red', line_color="red") plot.add_glyph(source, circle) plot.add_tools(*TOOLS) overlay = BoxSelectionOverlay(tool=box_select) plot.add_layout(overlay) doc = Document() doc.add(plot) if __name__ == "__main__": filename = "maps.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Google Maps Example"))
boroughs_ys=boroughs_ys, boroughs_colors=boroughs_colors, boroughsnames=boroughsnames, population=population, area=area, density=density)) patches = Patches(xs="boroughs_xs", ys="boroughs_ys", fill_color="boroughs_colors", fill_alpha=0.7, line_color="black", line_width=0.5) patches_glyph = p.add_glyph(source_patches, patches) p.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), HoverTool(), ResetTool(), PreviewSaveTool()) #xaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) #p.add_layout(xaxis, 'below') #yaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) #p.add_layout(yaxis, 'left') hover = p.select(dict(type=HoverTool)) #hover.snap_to_data = False # not supported in new bokeh versions hover.tooltips = OrderedDict([ ("Borough", "@boroughsnames"), ("Population", "@population"), ("Area (km2)", "@area"), # ("Density (pop/km2)", "@density"), # ("(long,lat)", "($x, $y)"), ])
def generateManhattan(manhattanData, treshold, phenotype, userWidth, userHeight): #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# max_v = int(manhattanData.log10.max()) #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# df_slice_dataframe = manhattanData.groupby( 'chromosome') # CUTS GWAS DATA TO COMPUTE GWAS'S POSITIONS counter = 0 dictionary_of_slices = { } # put slices of dataframe in a dictionnary for reforming whole dataframe chr_max_pos = [] # get maximum position to get middle after chr_min_pos = [] # get minimum positions to get middle after manhattan_max_pos = [ 0 ] # get maximum position for each chromosome for manhattan plotting df_concat_slice = [] for name, group in df_slice_dataframe: dictionary_of_slices[str(name)] = group chr_min_pos.append(int(dictionary_of_slices[str(name)]['pos'] [0:1])) #position min chromosome manhattan_max_pos.append( int(dictionary_of_slices[str(name)]['pos'] [len(dictionary_of_slices[str(name)]['pos']) - 1:len(dictionary_of_slices[str(name)]['pos'])]) + manhattan_max_pos[counter]) chr_max_pos.append( int(dictionary_of_slices[str(name)]['pos'] [len(dictionary_of_slices[str(name)]['pos']) - 1:len(dictionary_of_slices[str(name)]['pos'])]) ) #position max chromosome dictionary_of_slices[str( name)]['position'] = group['pos'] + manhattan_max_pos[counter] counter += 1 df_concat_slice.append(dictionary_of_slices[str(name)]) counter = 0 # full_data = pandas.concat( df_concat_slice ) #recreate original manhattan data with position column added #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# milieu = [] # HALF OF CHROMOSOME POSITIONS TO STORE name of chromosomes print chr_min_pos for n in range(1, len(manhattan_max_pos)): milieu.append(manhattan_max_pos[n - 1] + ((manhattan_max_pos[n] - manhattan_max_pos[n - 1]) // 2)) #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# # CREATE MANHATTAN PLOT #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# source = ColumnDataSource(full_data) # SOURCE DATA FOR BOKEH PLOT TOOLS = [ HoverTool(tooltips=[ ("SNP", "@rs_id_assoc"), ("Gene", "@gene"), ("P-value", "@pvalue_assoc"), ]), CrosshairTool(), WheelZoomTool(), BoxSelectTool(), BoxZoomTool(), ResizeTool(), ResetTool(), PanTool(), PreviewSaveTool(), TapTool() ] # BoxSelectTool(), BoxZoomTool(), plot = figure( webgl=True, title=phenotype, tools=TOOLS, x_axis_label='Chromosomes', y_axis_label='-log10(p)', plot_width=userWidth, plot_height=userHeight, y_range=(2.0, max_v + 3), ) #This is for "odd" chromosomes plot.circle('position', 'odd', source=source, size=3) #This is for "even" chromosomes plot.circle('position', 'even', source=source, size=3, color="black") plot.ray(x=[0], y=[-numpy.log10(treshold)], length=0, angle=0, color='red') plot.ray(x=[0], y=[-numpy.log10(treshold)], length=0, angle=numpy.pi, color='red') plot.axis.major_label_text_font_size = '0pt' plot.text(milieu, [2.75] * (len(milieu)), text=[ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22" ], text_color='black', text_align='center', text_font_size='8pt', text_font_style='bold') plot.text(milieu[(len(milieu) / 2) - 4], [2.25], text=["Chromosomes"], text_color='black', text_align='center', text_font_size='10pt', text_font_style='bold') plot.xaxis.major_tick_line_color = None plot.xaxis.minor_tick_line_color = None plot.xaxis.visible = None plot.grid.grid_line_color = None # TAKE GRID LINES OFF THE GRAPH graph, div1 = components(plot, CDN) return graph, div1
def compare_libraries_cnv_graphs(request): data = json.loads(request.body) colors = data['colors'] libcodes = data['libcodes'] chromosome = data['chromosome'] linestyles = data['linestyles'] charts = {} graph = figure(x_axis_label='Position (bp)', y_axis_label='CNV Values', title=chromosome, tools=[ BoxZoomTool(), PanTool(), HoverTool(tooltips=[("position", "@x"), ("CNV Value", "@y")]), ResetTool(), PreviewSaveTool() ], plot_height=800, plot_width=1300, toolbar_location="left") max_cnv = 0 for x in range(0, len(libcodes)): cnvvalues = [] positions = [] for cnvobject in CNV.objects.filter( library__library_code=libcodes[x]).filter( cnv_type__cvterm='CNV').filter( chromosome__chromosome_name=chromosome): cnvvalues.append(cnvobject.cnv_value) positions.append(cnvobject.stop) graph.line(x=positions, y=cnvvalues, legend=libcodes[x], line_color=colors[x], line_dash=linestyles[x], line_width=2) graph.xaxis[0].formatter = NumeralTickFormatter(format="0") graph.circle(x=positions, y=cnvvalues, fill_color=colors[x], size=4, color=colors[x]) graph.x_range = Range1d(0, positions[-1]) max_cnv = max(max_cnv, max(cnvvalues)) graph.y_range = Range1d(0, max_cnv + 5) script, div = components(graph) charts[chromosome] = [script, div] return HttpResponse(json.dumps(charts))
z = cos(x) source = ColumnDataSource(data=dict(x=x, y=y)) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, min_border=50) line_glyph = Line(x="x", y="y", line_color="blue") plot.add_glyph(source, line_glyph) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') pan = PanTool() wheel_zoom = WheelZoomTool() preview_save = PreviewSaveTool() plot.add_tools(pan, wheel_zoom, preview_save) doc = Document() doc.add_root(plot) if __name__ == "__main__": filename = "line.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Line Glyph Example")) print("Wrote %s" % filename) view(filename)
def showInteractiveDf(self, quotes): import time from math import pi import pandas as pd from bokeh.io import output_notebook from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource, Rect, HoverTool, Range1d, LinearAxis, WheelZoomTool, PanTool, ResetTool, ResizeTool, PreviewSaveTool import numpy as np output_notebook() quotes[quotes['volume']==0]=np.nan quotes= quotes.dropna() openp=quotes['open'] closep=quotes['close'] highp=quotes['high'] lowp=quotes['low'] volume=quotes['volume'] time=quotes.index date=[x.strftime("%Y-%m-%d") for x in quotes.index] quotes['date']=date w = 12*60*60*1000 # half day in ms mids = (openp + closep)/2 spans = abs(closep-openp) inc = closep > openp dec = openp > closep ht = HoverTool(tooltips=[ ("date", "@date"), ("open", "@open"), ("close", "@close"), ("high", "@high"), ("low", "@low"), ("volume", "@volume"), ("money", "@money"),]) TOOLS = [ht, WheelZoomTool(dimensions=['width']), ResizeTool(), ResetTool(),PanTool(dimensions=['width']), PreviewSaveTool()] max_x = max(highp) min_x = min(lowp) x_range = max_x - min_x y_range = (min_x - x_range / 2.0, max_x + x_range * 0.1) p = figure(x_axis_type="datetime", tools=TOOLS, plot_height=600, plot_width=950,toolbar_location="above", y_range=y_range) p.xaxis.major_label_orientation = pi/4 p.grid.grid_line_alpha=0.3 p.background_fill = "black" quotesdate=dict(date1=quotes['date'],open1=openp,close1=closep,high1=highp,low1=lowp) ColumnDataSource(quotesdate) x_rect_inc_src =ColumnDataSource(quotes[inc]) x_rect_dec_src =ColumnDataSource(quotes[dec]) p.rect(time[inc], mids[inc], w, spans[inc], fill_color="red", line_color="red", source=x_rect_inc_src) p.rect(time[dec], mids[dec], w, spans[dec], fill_color="green", line_color="green", source=x_rect_dec_src) p.segment(time[inc], highp[inc], time[inc], lowp[inc], color="red") p.segment(time[dec], highp[dec], time[dec], lowp[dec], color="green") show(p)
def create_plots(model1, model3, model4, model5, live_data, city, display_name): """ Output: Bokeh plot Creates individual timeseries plot """ if city != 'chicago': model1 = model1.query("city_{} == 1 and display_name_{} == 1".format( city, display_name)) # model2 = model2.query("city_{} == 1 and display_name_{} == 1".format(city, display_name)) model3 = model3.query("city_{} == 1 and display_name_{} == 1".format( city, display_name)) model4 = model4.query("city_{} == 1 and display_name_{} == 1".format( city, display_name)) model5 = model5.query("city_{} == 1 and display_name_{} == 1".format( city, display_name)) else: model1 = model1.query( "city_denver == 0 and city_seattle == 0 and city_sf == 0 and city_ny == 0 and display_name_{} == 1" .format(display_name)) # model2 = model2.query("city_denver == 0 and city_seattle == 0 and city_sf == 0 and city_ny == 0 and display_name_{} == 1".format(display_name)) model3 = model3.query( "city_denver == 0 and city_seattle == 0 and city_sf == 0 and city_ny == 0 and display_name_{} == 1" .format(display_name)) model4 = model4.query( "city_denver == 0 and city_seattle == 0 and city_sf == 0 and city_ny == 0 and display_name_{} == 1" .format(display_name)) model5 = model5.query( "city_denver == 0 and city_seattle == 0 and city_sf == 0 and city_ny == 0 and display_name_{} == 1" .format(display_name)) cartype = display_name.lower() live_data = live_data.query("display_name == @cartype and city == @city") source1 = ColumnDataSource(data=dict(d=model1['date'].astype(str), h=model1['hour'], f=model1['y_forecast'], n=model1['name'])) # source2 = ColumnDataSource( # data=dict( # d=model2['date'].astype(str), # h=model2['hour'], # f=model2['y_forecast'], # n=model2['name'] # ) # ) source3 = ColumnDataSource(data=dict(d=model3['date'].astype(str), h=model3['hour'], f=model3['y_forecast'], n=model3['name'])) source4 = ColumnDataSource(data=dict(d=model4['date'].astype(str), h=model4['hour'], f=model4['y_forecast'], n=model4['name'])) source5 = ColumnDataSource(data=dict(d=model5['date'].astype(str), h=model5['hour'], f=model5['y_forecast'], n=model5['name'])) source6 = ColumnDataSource(data=dict(d=live_data['date'].astype(str), h=live_data['hour'], f=live_data['avg_price_est'], n=live_data['name'])) hover = HoverTool(tooltips=[("Model", "@n"), ("Date", "@d"), ("Hour", "@h"), ("Average Price", "@f")]) change_city = { 'denver': 'Denver', 'ny': 'New York', 'chicago': 'Chicago', 'seattle': 'Seattle', 'sf': 'San Francisco' } p = figure(title="Forecast of {} {} Prices - {} to {}".format( change_city[city], display_name, sys.argv[1], sys.argv[2]), plot_width=1000, plot_height=500, x_axis_type="datetime", tools=[ hover, PanTool(), BoxZoomTool(), ResizeTool(), WheelZoomTool(), PreviewSaveTool(), ResetTool() ], toolbar_location="left", title_text_font_size="20pt") p.line(model1['record_time'], model1['y_forecast'], line_color='blue', line_width=2, legend="Random Forest Regressor", alpha=0.5, source=source1) # p.line(model2['record_time'], model2['y_forecast'], line_color='green', line_width=2, legend="RF Model 2 - Without Surge Multiplier", alpha=0.5, source=source2) # line_dash=[4,4] p.line(model3['record_time'], model3['y_forecast'], line_color='magenta', line_width=2, legend="Ridge Regression", alpha=0.5, source=source3) # line_dash=[4,4] p.line(model4['record_time'], model4['y_forecast'], line_color='gray', line_width=2, legend="ARIMA Model", alpha=0.5, source=source4) # line_dash=[4,4] p.line(model5['record_time'], model5['y_forecast'], line_color='green', line_width=2, legend="XGB Regressor", alpha=0.5, source=source5) # line_dash=[4,4] # p.xaxis.axis_label = 'Time' # p.xaxis.axis_label_text_font_size = "10pt" p.yaxis.axis_label = 'Average Price Estimate' p.yaxis.axis_label_text_font_size = "20pt" p.yaxis.axis_label_standoff = 15 p.xgrid[0].ticker.desired_num_ticks = 20 xformatter = DatetimeTickFormatter(formats=dict(hours=["%H"])) p.xaxis.formatter = xformatter p.legend.label_text_font_size = "10pt" # add a text renderer to out plot (no data yet) r = p.circle(x=live_data['record_time'], y=live_data['avg_price_est'], legend="True Average Prices", source=source6, color='red') ds = r.data_source return p, ds
zoom=13) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Washington, DC", plot_width=1280, plot_height=1280, responsive=True) # Finally plot it lines = MultiLine(xs="lons", ys="lats", line_alpha="line_alpha", line_width="line_width", line_color="red", line_cap="round") circle = Circle(x="lon", y="lat", size=10, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) plot.add_glyph(line_source, lines) plot.add_tools(PanTool(), WheelZoomTool(), BoxZoomTool(), hover, ResetTool(), UndoTool(), RedoTool(), PreviewSaveTool()) output_file("gmap_plot.html") show(plot)
r = np.tan(x) e = ColumnDataSource(dict(x=x, y=v)) f = ColumnDataSource(dict(x=x, y=r)) list_of_axis = [(a, b), (c, d), (e, f)] hover = HoverTool(tooltips=[ ("(x,y)", "($x, $y)"), ]) Tools = [ TapTool(), BoxZoomTool(), BoxSelectTool(), PreviewSaveTool(), ResetTool() ] def update_title(new, radio, sources): print("hello") active_source = sources[radio.active] factor = float(new) x = active_source.data["x"] y = factor * active_source.data["y"] active_source.data = dict(x=x, y=y)
def candlestick_volume_plot(input_df, plot_title=None): ''' Copyright Shawn Gu, 2016 The code below is modified based on the snippet from http://bokeh.pydata.org/en/0.11.1/docs/gallery/candlestick.html. ''' input_df = input_df.dropna() input_df['date'] = pd.to_datetime(input_df.index) px_mids = (input_df['open'] + input_df['close']) / 2.0 px_spans = abs(input_df['close'] - input_df['open']) vol_mids = input_df['vol'] / 2.0 vol_spans = input_df['vol'] max_vol = max(input_df['vol']) inc = input_df['close'] >= input_df['open'] dec = input_df['open'] > input_df['close'] inc_color = 'red' dec_color = 'green' width = 12 * 60 * 60 * 1000 # in ms ht = HoverTool(tooltips=[ ("date", "@date"), ("open", "@open"), ("close", "@close"), ("high", "@high"), ("low", "@low"), ]) TOOLS = [ ht, WheelZoomTool(dimensions=['width']), ResizeTool(), ResetTool(), PanTool(dimensions=['width']), PreviewSaveTool() ] max_px = max(input_df['high']) min_px = min(input_df['low']) px_range = max_px - min_px primary_y_range = (min_px - px_range / 10.0, max_px + px_range * 0.1) global p p = figure(x_axis_type="datetime", tools=TOOLS, plot_height=600, plot_width=1000, toolbar_location="above", y_range=primary_y_range) if plot_title: p.title = plot_title p.xaxis.major_label_orientation = pi / 4 p.grid.grid_line_alpha = 0.3 p.background_fill = "black" p.extra_y_ranges = {"vol": Range1d(start=0, end=max_vol * 5)} p.add_layout(LinearAxis(y_range_name="vol"), 'right') px_rect_inc_src = create_data_source(input_df[inc]) px_rect_dec_src = create_data_source(input_df[dec]) p.segment(input_df.date[inc], input_df.high[inc], input_df.date[inc], input_df.low[inc], color=inc_color) p.segment(input_df.date[dec], input_df.high[dec], input_df.date[dec], input_df.low[dec], color=dec_color) p.rect(input_df.date[inc], px_mids[inc], width, px_spans[inc], fill_color=inc_color, line_color=inc_color, source=px_rect_inc_src) p.rect(input_df.date[dec], px_mids[dec], width, px_spans[dec], fill_color=dec_color, line_color=dec_color, source=px_rect_dec_src) p.rect(input_df.date[inc], vol_mids[inc], width, vol_spans[inc], fill_color=inc_color, color=inc_color, y_range_name="vol") p.rect(input_df.date[dec], vol_mids[dec], width, vol_spans[dec], fill_color=dec_color, color=dec_color, y_range_name="vol") """自定义划线""" addlineplot(input_df) if plot_title: output_file(plot_title + "candlestick.html", title=plot_title) else: output_file("untitle_candlestick.html", title="untitled") show(p)
def generateAreaSelection(dataframe, userWidth, userHeight, position_min, position_max): snps = dataframe snps["log10"] = -numpy.log10(snps.pvalue_assoc) #transformation snps = snps.sort_values(by="pvalue_assoc") # SORT BY P-VALUE max_pvalue = int(snps.log10[0:1]) # GET MINIMUM P-VALUE #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# #NEW COLUMNS AND RENAMING #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# snps['imp'] = numpy.where(snps['info_assoc'] == 1, snps['log10'], 'NaN') # gather information on imputed snps snps['Imputed'] = numpy.where( snps['info_assoc'] == 1, True, False) #discriminate between imputed and genotyped for table snps['interest'] = numpy.where(snps['log10'] >= (-numpy.log10(0.00000005)), snps['log10'], 'NaN') #select snp of interest #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# source = ColumnDataSource(snps) # SOURCE DATA FOR BOKEH PLOT TOOLS = [ HoverTool(tooltips=[("SNP", "@rs_id_assoc"), ( "Gene", "@gene"), ("P-value", "@pvalue_assoc"), ("Region", "@func")]), CrosshairTool(), WheelZoomTool(), BoxSelectTool(), BoxZoomTool(), ResizeTool(), ResetTool(), PanTool(), PreviewSaveTool(), TapTool() ] stringLegend = "pvalue < " + str(0.001) plot = figure(webgl=True, tools=TOOLS, x_axis_label='Position', y_axis_label='-log10(p)', plot_width=userWidth, plot_height=userHeight, x_range=(position_min - 150000, position_max + 150000), y_range=(-3.2, max_pvalue + 3) # y_range = (-1, max_pvalue+1) ) plot.circle('position', 'log10', source=source, size=7, legend='Genotyped') plot.square('position', 'imp', source=source, size=7, color="olive", legend='Imputed') plot.circle('position', 'interest', source=source, size=7, color="red", legend=stringLegend) snps = snps.sort_values(by="position") # SORT POSITIONS snps.drop_duplicates(subset=('gene'), inplace=True, keep="last") # TAKE GENE NAME DUPLICATES OFF # for i in range(0,10): # snps['ligne'+str(i+1)] = snps.start_gen[i:len(snps):10] # snps['Fligne'+str(i+1)] = snps.end_gen[i:len(snps):10] # # positions = { # 'ligne1' : -0.30, # 'ligne2' : -0.55, # 'ligne3' : -0.85, # 'ligne4' : -1.15, # 'ligne5' : -2.95, # 'ligne6' : -2.65, # 'ligne7' : -2.35, # 'ligne8' : -2.05, # 'ligne9' : -1.75, # 'ligne10' : -1.45 # } # for key, value in positions.items(): # print key, value # plot.segment(snps[key], [value]*(len(snps)), snps['F'+key],[value]*(len(snps)), line_width=6, line_color="#8b4513",) #ligne 1 # # plot.text(snps[key]+((snps['F'+key]-snps[key])/2), [value-0.05]*(len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='5pt', text_font_style='bold') snps['ligne1'] = snps.start_gen[0:len(snps):10] snps['Fligne1'] = snps.end_gen[0:len(snps):10] snps['ligne2'] = snps.start_gen[1:len(snps):10] snps['Fligne2'] = snps.end_gen[1:len(snps):10] snps['ligne3'] = snps.start_gen[2:len(snps):10] snps['Fligne3'] = snps.end_gen[2:len(snps):10] snps['ligne4'] = snps.start_gen[3:len(snps):10] snps['Fligne4'] = snps.end_gen[3:len(snps):10] snps['ligne5'] = snps.start_gen[4:len(snps):10] snps['Fligne5'] = snps.end_gen[4:len(snps):10] snps['ligne6'] = snps.start_gen[5:len(snps):10] snps['Fligne6'] = snps.end_gen[5:len(snps):10] snps['ligne7'] = snps.start_gen[6:len(snps):10] snps['Fligne7'] = snps.end_gen[6:len(snps):10] snps['ligne8'] = snps.start_gen[7:len(snps):10] snps['Fligne8'] = snps.end_gen[7:len(snps):10] snps['ligne9'] = snps.start_gen[8:len(snps):10] snps['Fligne9'] = snps.end_gen[8:len(snps):10] snps['ligne10'] = snps.start_gen[9:len(snps):10] snps['Fligne10'] = snps.end_gen[9:len(snps):10] plot.segment( snps.ligne1, [-0.30] * (len(snps)), snps.Fligne1, [-0.30] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 1 plot.text(snps.ligne1 + ((snps.Fligne1 - snps.ligne1) / 2), [-0.25] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne2, [-0.55] * (len(snps)), snps.Fligne2, [-0.55] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 2 plot.text(snps.ligne2 + ((snps.Fligne2 - snps.ligne2) / 2), [-0.50] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne3, [-0.85] * (len(snps)), snps.Fligne3, [-0.85] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 3 plot.text(snps.ligne3 + ((snps.Fligne3 - snps.ligne3) / 2), [-0.80] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne4, [-1.15] * (len(snps)), snps.Fligne4, [-1.15] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 4 plot.text(snps.ligne4 + ((snps.Fligne4 - snps.ligne4) / 2), [-1.10] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne10, [-1.45] * (len(snps)), snps.Fligne10, [-1.45] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 5 plot.text(snps.ligne10 + ((snps.Fligne10 - snps.ligne10) / 2), [-1.40] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne9, [-1.75] * (len(snps)), snps.Fligne9, [-1.75] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 6 plot.text(snps.ligne9 + ((snps.Fligne9 - snps.ligne9) / 2), [-1.70] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne8, [-2.05] * (len(snps)), snps.Fligne8, [-2.05] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 7 plot.text(snps.ligne8 + ((snps.Fligne8 - snps.ligne8) / 2), [-2.00] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne7, [-2.35] * (len(snps)), snps.Fligne7, [-2.35] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 8 plot.text(snps.ligne7 + ((snps.Fligne7 - snps.ligne7) / 2), [-2.30] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne6, [-2.65] * (len(snps)), snps.Fligne6, [-2.65] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 9 plot.text(snps.ligne6 + ((snps.Fligne6 - snps.ligne6) / 2), [-2.60] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.segment( snps.ligne5, [-2.95] * (len(snps)), snps.Fligne5, [-2.95] * (len(snps)), line_width=6, line_color="#8b4513", ) #ligne 10 plot.text(snps.ligne5 + ((snps.Fligne5 - snps.ligne5) / 2), [-2.90] * (len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='1em', text_font_style='bold') plot.grid.grid_line_color = None # TAKE GRID LINES OFF THE GRAPH graph, div1 = components(plot, CDN) return graph, div1
ealpha=ealpha)) # plot ################ # Start timer t0 = time.time() ################ x_range = Range1d(0, 1) y_range = Range1d(0, 1) plot = Plot(x_range=x_range, y_range=y_range, plot_width=plot_width, plot_height=plot_height, title=title) plot.add_tools(PanTool(), WheelZoomTool(), BoxZoomTool(), PreviewSaveTool(), ResetTool()) # edges seg = Segment(x0="ex0", y0="ey0", x1="ex1", y1="ey1", \ line_width="ewidth",) seg_glyph = plot.add_glyph(esource, seg) # circles circ = Circle(x="x", y="y", size='size', line_color=None) circ_glyph = plot.add_glyph(nsource, circ) ################ # End Timer print(bokeh.__version__) print("Time to plot with Bokeh:", time.time() - t0, "seconds")