def plot_to_bokeh(data_frame, channels_names, desired_col_index=-1): ''' :param data_frame: pandas dataframe :param desired_col_index: -1 for all, i>0 for any other :return: non ''' if desired_col_index>=0: header_str = data_frame._info_axis.values[desired_col_index] col_data = data_frame._series[channels_names[desired_col_index]].values # returns nd_array # data_frame[data_frame._info_axis.values[3]] print col_data ################### output_file("iris.html") # Create the figure object f = figure() # adding glyphs f.circle(range(0,len(col_data)), col_data) # Save and show the figure show(f) print f ################### return col_data
def search(): error = None uh=urllib.urlopen('https://www.quandl.com/api/v3/datasets/WIKI/'+request.form['ticker']+'.json') qc=uh.read() js=json.loads(str(qc)) data=js["dataset"]["data"] t=int(request.form['cars']) stk=request.form['ticker'] table={1:'Open',2:'High',3:'Low',4:'Close',5:'Volume',6:'Ex-Dividend',7:'Split Ratio',8:'Adj. Open',9:'Adj. High',10:'Adj. Low',11:'Adj. Close',12:'Adj. Volume'} item=table[t] tit=item+' of '+stk+' (Data from Quandle WIKI)' date=[] acp=[] for i in data: a1=datetime.datetime.strptime(i[0], '%Y-%m-%d') date.append(datetime.date(a1.year,a1.month,a1.day)) acp.append(i[t]) np_acp=np.array(acp) output_file("./templates/output.html") p=figure(x_axis_type="datetime",title=tit,x_axis_label = "Date",y_axis_label = item) r=p.line(date,acp) show(p) #files = os.listdir(os.curdir) #return json.dumps({'error':files}) #flash(request.form['ticker']+' '+request.form['cars']) return render_template('output.html')
def show_map(country_xs, country_ys, country_colours, country_names, country_users, outputname, plot_title): print("Plotting values...") source = ColumnDataSource( data = dict( x = country_xs, y = country_ys, colour = country_colours, name = country_names, users = country_users ) ) # print(source) #output_notebook #outputfile instead output_file(outputname) tools = 'pan,wheel_zoom,box_zoom,reset,hover,save' p = figure( title=plot_title, tools=tools, plot_width=800 ) p.patches('x','y', fill_color = 'colour', fill_alpha = 0.7, line_color='white', line_width=0.5, source=source) hover = p.select(dict(type=HoverTool)) hover.point_policy = 'follow_mouse' hover.tooltips = OrderedDict([ ('Name','@name'), ('Number of Users','@users') ]) save(p)
def setOutput(self, comb): gr = self.keyFunc(comb) if gr not in self.files: self.files[gr] = [] fn = '%s_%s_%s.html'%(self.basename, gr, len(self.files[gr])) self.files[gr].append(fn) io.output_file(fn, **self.kw) return fn
def start(self): c = self.last_report() b = [i for sub in c for i in sub] graph = vform(*b) s = '../Report' + '/' + 'report_%s.html' % self.build[0].replace('.', '_') output_file(s, title=self.build[0] + '-' + self.devicename[0] + 'Report') return show(graph)
def plot_simple_bokeh_line(x,y, filename, height, width, xaxis, yaxis, title): output_file(filename) p=figure(plot_width=width, plot_height=height,title=title) p.line(x,y, color="green") p.xaxis.axis_label=xaxis p.yaxis.axis_label=yaxis show(p)
def create_map(tab_del_file): """ This function was adapted from bokeh tutorial, so it might have similar elements in it. """ data = pandas.read_csv(tab_del_file, sep="\\t", engine='python') lat_mean = data["Lat"].mean() long_mean = data["Long"].mean() map_options = GMapOptions(lat=lat_mean, lng=long_mean, map_type="hybrid", zoom=5) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="PopART-XTREME" ) source = ColumnDataSource(data=dict(lat=[x for x in data["Lat"]], lon=[y for y in data["Long"]], name=[s for s in data["Sequence"]], local=[l for l in data["Locality"]])) circle = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None) tooltips = [("Sequence", "@name"), ("Locality", "@local")] render = plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), BoxZoomTool(), PreviewSaveTool(), HoverTool(tooltips=tooltips, renderers=[render])) output_file("map_plot.html") show(plot)
def create_report_v2(energy=None, applicator=None, ssd=None, filepath=None, inverted_factor=False): width, length, eqPonA, factor, label = pull_data( energy=energy, applicator=applicator, ssd=ssd, return_label=True) if inverted_factor: factor = 1/factor tag = "!!INVERTED_FACTOR!!" else: tag = "" number_of_measurements = len(width) if number_of_measurements < 8: sufficient = False else: sufficient = True if filepath is None: filepath = ( "interactive_reports/" + str(energy) + "MeV_" + str(applicator) + "app_" + str(ssd) + "ssd_" + str(number_of_measurements) + "datapoints" + tag + ".html") output_file(filepath) if sufficient: result = interactive_v2(width, length, eqPonA, factor, label) show(result)
def create_heatmap(station_scores, plot_width=1000, plot_height=600): map_options = GMapOptions(lat=32.06, lng=34.87, map_type="roadmap", zoom=9) cmap = plt.get_cmap('jet') plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Israel" ) plot.plot_width = plot_width plot.plot_height = plot_height lat_vec = list(map(lambda x: get_loc_by_id(x).lat, station_scores.keys())) lon_vec = list(map(lambda x: get_loc_by_id(x).lon, station_scores.keys())) for ind, station in enumerate(station_scores): source = ColumnDataSource( data=dict( lat=[lat_vec[ind]], lon=[lon_vec[ind]], ) ) cmap_indx = int(station_scores[station]*cmap.N) cmap_val = tuple(np.floor(255 * np.array(cmap(cmap_indx)[:3]))) circle = Circle(x="lon", y="lat", size=17, fill_color=cmap_val, fill_alpha=0.95, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool()) output_file("Mean Time to Tel-Aviv Hashalom.html") show(plot)
def cop_graph(index): """ Make a graph of calls over puts """ output_file(index+".html") if index=="STOXX": id = 504880 elif index=="FTSE": id = 506528 elif index=="CAC": id = 506497 elif index=="DAX": id = 506496 else: raise Exception(ValueError) dfs = pd.read_csv(data_loc+"csv/CallOverPut.csv") dfs["Date"] = dfs.Date.apply(lambda x: dt.datetime.strptime(str(x), "%Y-%m-%d")) df = dfs[dfs["SecurityID"]==id][["Date", "CallOverPut"]] df = df.sort_values("Date") p = figure(title="Call Over Put - "+index, x_axis_type="datetime", plot_width=plot_width, toolbar_location='left') p.line(df["Date"], df["CallOverPut"], color=Spectral4[0]) p.line(df["Date"], pd.rolling_mean(df["CallOverPut"], 10), color=Spectral4[3]) p.legend.location = "top_left" p.xgrid[0].ticker.desired_num_ticks = 13 """script, div = components(p) with open(server_loc+index+"_CallsOverPuts_div.html", 'w') as f: f.write(div) with open(server_loc+index+"_CallsOverPuts_script.html", 'w') as f: f.write(script)""" return p
def make_map(self, map_type, title): options = GMapOptions(lat=43.7, lng=-79.4, map_type=map_type, zoom=11) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=options, title=title) output_file('plot.html') show(plot)
def lcoe_plot(self, fig): from plot_lcoe_csm import plot_lcoe from bokeh.io import show, output_file fig = plot_lcoe(self) output_file('bokeh plot', title='Bokeh Plot') #show(fig) return fig
def save(self, title='Training Results'): if len(self.figures) > 0: if os.path.isfile(self.plot_path): os.remove(self.plot_path) output_file(self.plot_path, title=title) plot = column(*self.figures) save(plot) self.clear() self.results.to_csv(self.path, index=False, index_label=False)
def output_charts(self,name,period, bot,top,fast_k,fast_d): candlestick = self.candlestick(name) rsi = self.rsi(candlestick,period,bot,top) stoch_rsi = self.stoch_rsi(candlestick,period,fast_k,fast_d) macd = self.macd(candlestick) self.plot_results(candlestick,rsi,stoch_rsi,macd) l=layout([[candlestick], [rsi],[stoch_rsi],[macd]]) output_file("charts/"+name.replace("/","")+".html",title="Crypto chart for "+name) #show(l) save(l)
def output_file_url(request, base_url): filename = request.function.__name__ + '.html' file_path = request.fspath.dirpath().join(filename).strpath output_file(file_path) def fin(): os.remove(file_path) request.addfinalizer(fin) return '%s/%s' % (base_url, file_path)
def c_graph(index, sel_implied, sel_realized, x): output_file("CorrGraph.html") c2 = figure(title=index+"\nCorrelation", x_axis_type='datetime', plot_width=plot_width, plot_height=275, x_range=x.x_range) c2.line(sel_implied["Date"], sel_implied["corr"], legend="Implied Correlation", line_width=2, color=Spectral4[1]) """c2.line(sel_realized["Date"], sel_realized["corr"], legend="Realized Correlation", line_width=2, color=Spectral4[2])""" c2.legend.location = "top_left" c2.xgrid[0].ticker.desired_num_ticks = 12 return c2
def box_plot_sim_game(df_results_team): # values to represent # score, two_pt_shots_attempt/made, three_pt_shots_made/attempts, off/def rebounds rel_col = [ 'PTS', 'FGA', 'FGM', 'FG3A', 'FG3M', 'OREB', 'DREB', 'STL', 'BLK', 'TO', 'PASS' ] # get quartile info # q4=min, q5=max q1, q2, q3, q4, q5 = {}, {}, {}, {}, {} for col in rel_col: q1[col] = df_results_team[col].quantile(q=0.25) q2[col] = df_results_team[col].quantile(q=0.50) q3[col] = df_results_team[col].quantile(q=0.75) q4[col] = df_results_team[col].quantile(q=0.00) q5[col] = df_results_team[col].quantile(q=1.00) df = pd.DataFrame([q1, q2, q3, q4, q5]).T df.columns = ['q{}'.format(i) for i, col in enumerate(df, 1)] iqr = df.q3 - df.q1 upper = df.q3 + 1.5 * iqr lower = df.q1 - 1.5 * iqr new_upper = [min([x, y]) for (x, y) in zip(df.q5.values, upper.values)] new_lower = [max([x, y]) for (x, y) in zip(df.q4.values, lower.values)] p = figure(tools="save", background_fill_color="#EFE8E2", title="", x_range=rel_col) # stems p.segment(rel_col, new_upper, rel_col, df.q3.values, line_color="black") p.segment(rel_col, new_lower, rel_col, df.q1.values, line_color="black") # boxes p.vbar(rel_col, 0.7, df.q2.values, df.q3.values, fill_color='#FF1493', line_color="black") p.vbar(rel_col, 0.7, df.q1.values, df.q2.values, fill_color='#1E90FF', line_color="black") # whiskers (almost-0 height rects simpler than segments) p.rect(rel_col, new_lower, 0.2, 0.01, line_color="black") p.rect(rel_col, new_upper, 0.2, 0.01, line_color="black") p.xgrid.grid_line_color = None p.ygrid.grid_line_color = "white" p.grid.grid_line_width = 2 p.xaxis.major_label_text_font_size = "12pt" output_file("box.html") show(p)
def output_file_url(request, file_server): filename = request.function.__name__ + '.html' file_obj = request.fspath.dirpath().join(filename) file_path = file_obj.strpath url = file_path.replace('\\', '/') # Windows-proof output_file(file_path, mode='inline') def tearDown(): if file_obj.isfile(): file_obj.remove() request.addfinalizer(tearDown) return file_server.where_is(url)
def main(): # Create Plot plot = create_plot() # Load Asset Glyphs with open('asset_data.json', 'r') as f: asset_json = json.loads(f.read()) for asset in asset_json['assets']: plot_asset(plot, asset) # Display Plot output_file("county_map.html") show(plot)
def output_file_url(request, base_url): filename = request.function.__name__ + '.html' file_obj = request.fspath.dirpath().join(filename) file_path = file_obj.strpath output_file(file_path, mode='inline') def tearDown(): if file_obj.isfile(): file_obj.remove() request.addfinalizer(tearDown) return '%s/%s' % (base_url, file_path)
def output_file_url(request, file_server): filename = request.function.__name__ + ".html" file_obj = request.fspath.dirpath().join(filename) file_path = file_obj.strpath output_file(file_path, mode="inline") def tearDown(): if file_obj.isfile(): file_obj.remove() request.addfinalizer(tearDown) return file_server.where_is(file_path)
def func(self, args): applications = self.build_applications(args) for (route, app) in applications.items(): doc = app.create_document() if route == "/": filename = "index.html" else: filename = route[1:] + ".html" output_file(filename) if args.show: show(doc, new='tab') else: save(doc)
def v_graph(index, sel_implied, sel_realized, x): output_file("VGraph.html") p = figure(title="ATM Volatility (3 Month)", x_axis_type='datetime', plot_width=plot_width, plot_height=500, x_range=x.x_range) p.line(sel_implied["Date"], sel_implied["idx_IVol"], legend="Implied Volatility", line_width=2, color=Spectral4[0]) """p.line(sel["Date"], sel["average_IVol"], legend="Average IVol of Constituents", line_width=2, color=Spectral4[1])""" p.line(sel_implied["Date"], sel_realized["idx_HistVol"], legend="Realized Volatility", line_width=2, color=Spectral4[1]) p.legend.location = "top_left" p.xgrid[0].ticker.desired_num_ticks = 13 return p
def plot_nodecounts_bokeh_line(): datasets_csv = read_datasets_csv() datasets = sorted([dataset['name'] for dataset in datasets_csv]) plots = [] for dataset in datasets: output_file(PNG_FOLDER + dataset + '_nodes.html') x,y=get_node_counts_for_cutoffs(dataset=dataset) p = figure(title='node counts for ' + dataset, tools="pan,wheel_zoom,box_zoom,previewsave,reset") p.xaxis.axis_label='cut-off' p.yaxis.axis_label='# nodes' p.line(x,y, color="green") save(p) plots.append(p) output_file(TEMPLATE_FOLDER + 'bokeh_nodecount.html') gp = gridplot(plots, ncols=2, tools="pan,wheel_zoom,box_zoom,save,reset") save(gp)
def get_graph(df, checkboxes, ticker): output_file('boken_file.html') x = df.Date p = figure(x_axis_type="datetime") p.xaxis.axis_label = 'Date' if checkboxes.op: p.line(datetime(x), df.Open, color='#A6CEFF', legend='Open Price ') if checkboxes.aop: p.line(datetime(x), df['Adj. Open'], color='#CB112A', legend='Adj. Open Price') if checkboxes.cp: p.line(datetime(x), df.Close, color='#FF9A99', legend='Close Price') if checkboxes.acp: p.line(datetime(x), df['Adj. Close'], color='#33A02C', legend='Adj. Close Price') script, div = components(p, CDN) return script, div
def makeFeaturePlots(modelFolder, outputFolder, drugName): clf = joblib.load(modelFolder + drugName) output_file(outputFolder + drugName + ".html", title = drugName + ' Features') featureDataFrame = joblib.load('../output/emptyDataFrame.pkl') featureDataFrame['Feature Importance'] = clf.coef_ featureDataFrame.sort(columns='Feature Importance', inplace=True) resistanceGenes= featureDataFrame.index.values[:25] resistanceValues= featureDataFrame['Feature Importance'].values[:25] featureDataFrame.sort(columns='Feature Importance', inplace=True, ascending= False) sensitivityGenes = featureDataFrame.index.values[:25] sensitivityValues = featureDataFrame['Feature Importance'].values[:25] s1 = Bar(resistanceValues, cat=resistanceGenes.tolist(), title="Top 25 Resistance Genes for " + drugName, xlabel='Genes', ylabel = 'Coefficient', width=800, height=400, tools = False) s2 = Bar(sensitivityValues, cat=sensitivityGenes.tolist(), title="Top 25 Senitivity Genes for " + drugName, xlabel='Genes', ylabel = 'Coefficient', width=800, height=400, tools = False, palette = ['#82CC9B']) p = vplot(s1, s2) show(p)
def print_graphs(scores): output_file(s.plots + ".html") properties_per_dataset = { 'train': {'line_color': 'firebrick'}, 'test': {'line_color': 'orange'}, 'valid': {'line_color': 'olive'} } plots = [] for metric in ConfusionMatrix._fields: plot = figure(width=500, plot_height=500, title=metric) for dataset_name in scores: metric_scores = [score.value for score in scores[dataset_name][metric]] plot.line(range(len(metric_scores)), metric_scores, legend=dataset_name, **properties_per_dataset[dataset_name]) plots.append(plot) p = vplot(*plots) save(p)
def bokeh_test(): # Let's plot a simple 5x5 grid of squares, alternating in color as red and blue. plot_values = [1, 2, 3, 4, 5] plot_colors = ["red", "blue"] # How do we tell Bokeh to plot each point in a grid? Let's use a function that # finds each combination of values from 1-5. from itertools import product grid = list(product(plot_values, plot_values)) print(grid) # The first value is the x coordinate, and the second value is the y coordinate. # Let's store these in separate lists. xs, ys = zip(*grid) print(xs) print(ys) # Now we will make a list of colors, alternating between red and blue. colors = [plot_colors[i % 2] for i in range(len(grid))] print(colors) # Finally, let's determine the strength of transparency (alpha) for each point, # where 0 is completely transparent. alphas = np.linspace(0, 1, len(grid)) # Bokeh likes each of these to be stored in a special dataframe, called # ColumnDataSource. Let's store our coordinates, colors, and alpha values. source = ColumnDataSource( data={ "x": xs, "y": ys, "colors": colors, "alphas": alphas, } ) # We are ready to make our interactive Bokeh plot! output_file("Basic_Example.html", title="Basic Example") fig = figure(tools="resize, hover, save") fig.rect("x", "y", 0.9, 0.9, source=source, color="colors", alpha="alphas") hover = fig.select(dict(type=HoverTool)) hover.tooltips = { "Value": "@x, @y", } show(fig)
def bubble_chart(input_file,output_myfile): '''Creates a bubble chart from input data, for a specific example. Will be made more generic soon. Input is a csv file, outputs an html file''' # Read in data from a csv file to a dataframe mydata = pd.read_csv(input_file) mycolors1 = bp.BrBG11 mycolors2 = bp.Spectral11 mycolors3 = bp.PRGn11 mycolors4 = bp.PiYG11 mycolors5 = bp.BrBG11 mycolors6 = bp.Spectral7 mycolors = mycolors1+mycolors2+mycolors3+mycolors4+mycolors5+mycolors6 #mycolors = bp.PiYG11 # Use ColumnDataSource to configure data source = ColumnDataSource(data = dict(names = mydata['Researcher Name'],fap = mydata['First Author Publications'], cap = mydata['Corresponding Author Publication'],tp = mydata['Total Publications'], ia = mydata['iclikval annotations'], coun = mydata['Country'])) output_file(output_myfile) # output filename html page hover = HoverTool(tooltips = [("Name","@names"),("Country","@coun"),("No: first author papers", "@fap"), ("No: corresponding author publications","@cap")]) myplot = figure(plot_width = 1200,plot_height = 600,tools = [hover,"pan","reset","box_zoom","wheel_zoom"]) myplot.xaxis.axis_label = "Total number of peer-reviewed publications" myplot.yaxis.axis_label = "Number of iCLiKVAL annotations" myplot.circle('tp','ia', size = 'fap',line_color = "navy",fill_color = mycolors,source = source) # Write out the bubble chart as html file save(myplot)
def subplot(): ## Make sure we are accessing the chromosomes in the correct order for key in range(1,23): print "Building subplot {}".format(key) TOOLTIPS=[ #( "index", "$index" ), ( 'X', '$x' ), ( 'Y', '$y' ), ] local_vars = vars() local_vars['p{}'.format(key)] = figure(plot_height=500, plot_width=500, output_backend="webgl", title="Chromosome {}".format(key)) local_vars['p{}'.format(key)].circle(x = data_dict[key].index.values, y = data_dict[key]['CEU'], color = "grey" ) local_vars['p{}'.format(key)].circle(x = data_dict[key].index.values, y = data_dict[key]['CDX'], color = "skyblue" ) local_vars['p{}'.format(key)].circle(x = data_dict[key].index.values, y = data_dict[key]['YRI'], color = "goldenrod" ) local_vars['p{}'.format(key)].circle(x = data_dict[key].index.values, y = data_dict[key]['Khoisan'], color = "salmon" ) local_vars['p{}'.format(key)].xaxis.major_label_orientation = "vertical" local_vars['p{}'.format(key)].xaxis[0].formatter.use_scientific = False local_vars['p{}'.format(key)].xaxis[0].ticker = [int(data_dict[key].first_valid_index()) ,int(data_dict[key].last_valid_index())] local_vars['p{}'.format(key)].x_range = Range1d(int(data_dict[key].first_valid_index()) ,int(data_dict[key].last_valid_index())) #output_file("Rf_chr{}.html".format(key)) export_svgs(local_vars['p{}'.format(key)], filename="Rfmix_intro_{}.svg".format(key)) #save(local_vars['p{}'.format(key)]) plot_list = [local_vars['p{}'.format(i)] for i in data_dict.keys()] #Make one figure out of the 22 subplots p =gridplot(plot_list, ncols=10) #p = row(plot_list) output_file("Rfmix_introgression.html") print "Saving to output - this could take a while.." save(p)
count=counts ) plot = figure(title="Matrix Author Similarity", x_axis_location="above", x_range=list(reversed(names1)), y_range=names1, toolbar_location = 'below') hover = HoverTool(tooltips = [('Names', '@yname, @xname'), ('Value', '@count')]) plot.add_tools(hover) plot.add_tools(BoxSelectTool(dimensions=["width", 'height'])) plot.plot_width = 1000 plot.plot_height = 1000 plot.grid.grid_line_color = None plot.axis.axis_line_color = None plot.axis.major_tick_line_color = None plot.axis.major_label_text_font_size = "5pt" plot.axis.major_label_standoff = 0 plot.xaxis.major_label_orientation = np.pi/3 plot.rect('xname', 'yname', 0.9, 0.9, source=data1, line_color=None, hover_line_color='black', fill_color={'field': 'count', 'transform': mapper}) plot.add_layout(color_bar, 'right') alpha_panel = Panel(child = p, title = 'Alpha model') color_panel = Panel(child = plot, title = 'Color model') tabs1 = Tabs(tabs = [alpha_panel, color_panel]) output_file("Matrix.html") show(tabs1) # show the plot
### Class end - Main start if __name__ == '__main__': # Initialize and load data reader = ibm_weather_csv('DronePlanning/CleanedObservationsOdense.csv', 'Odense', 2016, MaxOperationWindSpeed_def, MaxOperationWindGusts_def, OperationMinTemperature_def, OperationMaxTemperature_def, debug=True) reader.loadCSV() # Output to static HTML file output_file("webpages/output.html", title="Drone planning using weather data") # %%%%%%%%%%%%%%%%%% WIND VISUALIZATION %%%%%%%%%%%%%%%%%% # %%%%%%%%% time plot of WIND SPEED and GUST - START %%%%%%%%% # create a new plot p1 = reader.createTimePlot('Wind', 'Date and time', 'Wind speed [m/s]') # Plot content p1.line(reader.DateSGMT, reader.SurfaceWindGustsMpsS, legend="Wind gusts - %s" % reader.city, alpha=0.8, color="green") p1.line(reader.DateSGMT, reader.WindSpeedMpsS, legend="Wind speed - %s" % reader.city,
------------------------------------------------------------------------------- ''' fig_title = 't Distribution and p-value' fig_path = os.path.join(images_dir, 'tdist.html') fig = figure(title=fig_title, plot_height=600, plot_width=1000, x_axis_label='t-statistic', x_range=(x_min, x_max), y_axis_label='pdf f(t|df)', y_range=(y_min, y_max), toolbar_location=None) # Output to HTML file output_file(fig_path, title=fig_title) # Set title font size and axes font sizes fig.title.text_font_size = '15.5pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.xaxis.ticker = SingleIntervalTicker(interval=10, num_minor_ticks=1) # fig.xgrid.ticker = SingleIntervalTicker(interval=10) # fig.xaxis.major_label_overrides = dict(zip([0, t_i], ['0', '|t_i|'])) fig.yaxis.ticker = SingleIntervalTicker(interval=0.1, num_minor_ticks=2) fig.ygrid.ticker = SingleIntervalTicker(interval=10)
p.js_on_event(events.MouseWheel, display_event(div, attributes=point_attributes + ['delta'])) # Mouse move, enter and leave p.js_on_event(events.MouseMove, display_event(div, attributes=point_attributes)) p.js_on_event(events.MouseEnter, display_event(div, attributes=point_attributes)) p.js_on_event(events.MouseLeave, display_event(div, attributes=point_attributes)) # Pan events pan_attributes = point_attributes + ['delta_x', 'delta_y'] p.js_on_event(events.Pan, display_event(div, attributes=pan_attributes)) p.js_on_event(events.PanStart, display_event(div, attributes=point_attributes)) p.js_on_event(events.PanEnd, display_event(div, attributes=point_attributes)) # Pinch events pinch_attributes = point_attributes + ['scale'] p.js_on_event(events.Pinch, display_event(div, attributes=pinch_attributes)) p.js_on_event(events.PinchStart, display_event(div, attributes=point_attributes)) p.js_on_event(events.PinchEnd, display_event(div, attributes=point_attributes)) # Selection events p.js_on_event(events.SelectionGeometry, display_event(div, attributes=['geometry', 'final'])) output_file("js_events.html", title="JS Events Example") show(layout)
# Make a simple Bokeh line graph from bokeh.plotting import figure from bokeh.io import output_file, show import pandas #prepare some data df = pandas.read_csv('data.csv') x = df['x'] y = df['y'] #prepare the output file output_file('Line_from_csv.html') #Create a figure object f = figure() #Create line plot f.line(x, y) show(f)
# Bokeh Libraries from bokeh.io import output_file from bokeh.plotting import figure, show # The figure will be rendered in statis HTML file called output_test_file.html output_file('output_test_file.html', title='Empty Bokeh Figure') fig = figure(background_fill_color='gray', background_fill_alpha=0.5, border_fill_color='blue', border_fill_alpha=0.25, plot_height=300, plot_width=500, h_symmetry=True, x_axis_label='X Label', x_axis_type='datetime', x_axis_location='above', x_range=('2018-01-01', '2018-06-30'), y_axis_label='Y Label', y_axis_type='linear', y_axis_location='left', y_range=(0, 100), title='Example Figure', title_location='right', toolbar_location='below', tools='save') # Remove the gridlines from the figure() object fig.grid.grid_line_color = None show(fig)
from bokeh.plotting import figure from bokeh.io import show, output_file from bokeh.models import Range1d, LabelSet, ColumnDataSource from scipy.interpolate import interp1d import numpy as np output_file( 'N:\CODING\Python\Projetos\FQ\Casa\cozinha\Microondas\magnetico\micro magnetico t.html' ) d = [0.000, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30] b = [66.18, 20.60, 12.54, 7.226, 4.594, 2.295, 1.839] g = interp1d(d, b, kind='quadratic') d2 = np.linspace(0, 0.3, 1000) b2 = g(d2) f = figure(plot_height=300, title='Micro-ondas (parte traseira)- Campo magnético', toolbar_location='above') source = ColumnDataSource(dict(x=d, y=b)) labels = LabelSet(x='x', y='y', text='y', level='glyph', x_offset=10, y_offset=5, source=source, render_mode='canvas') f.add_layout(labels)
def display_EOD(programs, pb, indicators, name, demand, electricity_prices=[], printIndicators=True): # defaults.height=400 # defaults.width = 400 demand = pb.demand #print(isnotebook()) areas = [] def time_step_hour(i): return pb.time_step_to_string(i) area1 = plot_lines(programs, time_step_hour) area1.title.text = "Production plans" areas.append(area1) colors_instruction = {} if max(pb.wind_power) > 0.1 or max(pb.solar_power) > 0.1: programs["Renewable"] = [ pb.wind_power[index] + pb.solar_power[index] for index, elt in enumerate(pb.wind_power) ] if max(pb.sold_local_production) > 0.1: programs["sold_local_production"] = [ pb.sold_local_production[index] for index, elt in enumerate(pb.wind_power) ] if max(pb.auto_conso) > 0.1: programs["auto_conso"] = [ pb.auto_conso[index] for index, elt in enumerate(pb.auto_conso) ] for key in programs: if "Hydro" in key: colors_instruction[key] = "blue" elif "Renewable" in key: colors_instruction[key] = "green" elif "sold" in key: colors_instruction[key] = "green" elif "auto_conso" in key: colors_instruction[key] = "grey" else: colors_instruction[key] = "purple" area2 = stack_lines(programs, time_step_hour, ylabel="MW", colors_instruction=colors_instruction) area2.title.text = "Cumulative production" #area2 = plot_lines(demand, time_step_hour) area2.line([i + 0.5 + j for i in range(len(demand)) for j in [0, 1]], [elt for elt in demand for j in [0, 1]], line_width=3, line_color="red", legend_label="Demand") areas.append(area2) if printIndicators == True: data = dict(indicator=[indicator for indicator in indicators], value=[indicators[indicator] for indicator in indicators]) source = ColumnDataSource(data) columns = [ TableColumn(field="indicator", title="indicator"), TableColumn(field="value", title="value"), ] area3 = DataTable(source=source, columns=columns, width=400, height=280) areas.append(area3) if (len(electricity_prices) > 0): area4 = plot_lines({"price": electricity_prices}, time_step_hour, ylabel="euros/MWh") area4.title.text = "Electricity_price" areas.append(area4) output_file("global_programs.html", title=name, mode="inline") # handle=show(row(areas)) # push_notebook(handle=handle) save(row(areas))
def save_plot(plot, plot_title="", html_filename="plot"): output_file(html_filename + ".html", mode="inline", title=plot_title) save(plot) path = os.path.join(os.getcwd(), html_filename + ".html") print("Plot file " + path + " saved.")
G = nx.karate_club_graph() plot = Plot(plot_width=400, plot_height=400, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) plot.title.text = "Graph Interaction Demonstration" plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool()) graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0]) graph_renderer.node_renderer.selection_glyph = Circle( size=15, fill_color=Spectral4[2]) graph_renderer.node_renderer.hover_glyph = Circle( size=15, fill_color=Spectral4[1]) graph_renderer.edge_renderer.glyph = MultiLine( line_color="#CCCCCC", line_alpha=0.8, line_width=5) graph_renderer.edge_renderer.selection_glyph = MultiLine( line_color=Spectral4[2], line_width=5) graph_renderer.edge_renderer.hover_glyph = MultiLine( line_color=Spectral4[1], line_width=5) graph_renderer.selection_policy = NodesAndLinkedEdges() graph_renderer.inspection_policy = EdgesAndLinkedNodes() plot.renderers.append(graph_renderer) output_file("interactive_graphs.html") show(plot)
from bokeh.io import show, output_file from bokeh.plotting import figure from bokeh.models import ColumnDataSource, Range1d, FactorRange, DataRange1d import pandas as pd output_file("bar_basic.html") book_fee=0 airline_fee=0 percent_fee=0 df = pd.read_csv("FB - real_exp diff per segment source for bokeh.csv") df = df.sort_values(by=['diff'], ascending=False) bid_list = [str(x) for x in df['bid']] df['real_price'] = [float(str(x).replace(',','')) for x in df['real_price']] df['expected_price'] = [float(str(x).replace(',','')) for x in df['expected_price']] df['bid'] = bid_list df = df.set_index('bid') new_diffs = [] base_fare = [] for bid in df.index: diff, pax_number, segments, price, expected_price = df.loc[bid, 'diff'], df.loc[bid,'pax_number'], df.loc[bid,'number_of_segments'], df.loc[bid,'real_price'],df.loc[bid,'expected_price'] bf, af, pf = df['book_fee'][bid], df['airline_fee'][bid], df['fee_percent'][bid] diff = diff + (bf*pax_number) + af if pf > 0: diff=diff + price*(pf/100) new_diff = diff - ((book_fee*pax_number*segments) + (airline_fee*segments))
* Make a ColumnDataSource called source with x set to the fertility column, y set to the life column and country set to the Country column. For all columns, select the rows with index value 1970. This can be done using data.loc[1970].column_name. ''' # Perform necessary imports from bokeh.io import output_file, show from bokeh.plotting import figure from bokeh.models import HoverTool, ColumnDataSource # Make the ColumnDataSource: source source = ColumnDataSource( data={ 'x': data.loc[1970].fertility, 'y': data.loc[1970].life, 'country': data.loc[1970].Country, }) # Create the figure: p p = figure(title='1970', x_axis_label='Fertility (children per woman)', y_axis_label='Life Expectancy (years)', plot_height=400, plot_width=700, tools=[HoverTool(tooltips='@country')]) # Add a circle glyph to the figure p p.circle(x='x', y='y', source=source) # Output the file and show the figure output_file('gapminder.html') show(p)
#Importing libraries from bokeh.plotting import figure from bokeh.io import output_file, show from bokeh.sampledata.iris import flowers from bokeh.models import Range1d, PanTool, ResetTool, HoverTool, ColumnDataSource, LabelSet colormap={'setosa':'red','versicolor':'green','virginica':'blue'} flowers['color'] = [colormap[x] for x in flowers['species']] flowers['size'] = flowers['sepal_width'] * 4 setosa = ColumnDataSource(flowers[flowers["species"]=="setosa"]) versicolor = ColumnDataSource(flowers[flowers["species"]=="versicolor"]) virginica = ColumnDataSource(flowers[flowers["species"]=="virginica"]) #Define the output file path output_file("iris.html") #Create the figure object f = figure() #adding glyphs f.circle(x="petal_length", y="petal_width", size='size', fill_alpha=0.2, color="color", line_dash=[5,3], legend='Setosa', source=setosa) f.circle(x="petal_length", y="petal_width", size='size', fill_alpha=0.2, color="color", line_dash=[5,3], legend='Versicolor', source=versicolor) f.circle(x="petal_length", y="petal_width", size='size', fill_alpha=0.2, color="color", line_dash=[5,3], legend='Virginica', source=virginica)
# -*- coding: utf-8 -*- from bokeh.io import show, output_file from fnsservice.fns.views import DublicatedGraph g = DublicatedGraph(width=800, height=800, N=1500) p = g.get_graph() output_file("graph.html") show(p)
import networkx as nx from bokeh.io import show, output_file from bokeh.plotting import figure from bokeh.models.graphs import from_networkx G=nx.karate_club_graph() plot = figure(title="Networkx Integration Demonstration", x_range=(-1.1,1.1), y_range=(-1.1,1.1), tools="", toolbar_location=None) graph = from_networkx(G, nx.spring_layout, scale=2, center=(0,0)) plot.renderers.append(graph) output_file("networkx_graph.html") show(plot)
from bokeh.plotting import figure from bokeh.io import output_file,show,save import pandas as pd df=pd.read_csv("http://pythonhow.com/data/bachelors.csv") x=df['Year'] y=df['Engineering'] output_file("../nb/ch1/data_csv_womens.html") f1=figure() f1.line(x,y) show(f1)
from bokeh.plotting import ColumnDataSource df = pd.read_csv('../datasets/gapminder_tidy.csv').dropna() america_df = df[df.region.str.contains('America')].groupby('Country').mean() africa_df = df[df.region.str.contains('Africa')].groupby('Country').mean() america = ColumnDataSource(america_df) africa = ColumnDataSource(africa_df) p = figure( x_axis_label='fertility (children per woman)', y_axis_label='life') ''' INSTRUCTIONS * Add a red circle glyph to the figure p using the latin_america ColumnDataSource. Specify a size of 10 and legend of America. * Add a blue circle glyph to the figure p using the africa ColumnDataSource. Specify a size of 10 and legend of Africa. ''' # Add the first circle glyph to the figure p p.circle('fertility', 'life', source=america, size=10, color='red', legend='America') # Add the second circle glyph to the figure p p.circle('fertility', 'life', source=africa, size=10, color='blue', legend='Africa') # Specify the name of the output_file and show the result output_file('fert_life_groups.html') show(p)
# -*- coding: utf-8 -*- """ Created on Thu Oct 4 11:26:43 2018 @author: bruno """ from bokeh.io import output_file, show from bokeh.layouts import gridplot from bokeh.models import ColumnDataSource from bokeh.plotting import figure output_file("brushing.html") x = list(range(-20, 21)) y0 = [abs(xx) for xx in x] y1 = [xx**2 for xx in x] # create a column data source for the plots to share source = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1)) TOOLS = "box_select,lasso_select,help, reset" # create a new plot and add a renderer left = figure(tools=TOOLS, plot_width=300, plot_height=300, title=None) left.circle('x', 'y0', source=source) # create another new plot and add a renderer right = figure(tools=TOOLS, plot_width=300, plot_height=300, title=None) right.circle('x', 'y1', source=source)
from bokeh.plotting import figure from bokeh.io import output_file, show x = [3, 7, 5, 10] y = [3, 6, 9, 11] output_file('triangle.html') f = figure() f.triangle(x, y) show(f)
'virginica':'https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Iris_virginica.jpg/800px-Iris_virginica.jpg'} flowers['imgs'] = [urlmap[x] for x in flowers['species']] setosa = ColumnDataSource(flowers.loc[flowers["species"]=="setosa",:]) versicolor = ColumnDataSource(flowers.loc[flowers["species"]=="versicolor",:]) virginica = ColumnDataSource(flowers.loc[flowers["species"]=="virginica",:]) ds={} ds['setosa'] = {'dsrc':setosa, 'label':"Setosa"} ds['versicolor'] = {'dsrc':versicolor, 'label':"Versicolor"} ds['virginica'] = {'dsrc':virginica, 'label':"Virginica"} #Define the output file path output_file("nb/ch3/iris.html") #Create the figure object f = figure() #adding glyphs for k in ds.keys(): f.circle(x="petal_length", y="petal_width", size='size', fill_alpha=0.2, color="color", line_dash=[5,3], legend=ds[k]['label'], source=ds[k]['dsrc']) #calls columnDataSource #style the tools f.tools = [PanTool(),ResetTool()]
def Photon_Output_Graph(conn): output_file( "Photon_Output_Graph.html" ) #???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ############################################################################ ############################# USER INPUTS ################################## # Decide what the default viewing option is going to be. (i.e. the fields to # be plotted on the x and y axis when the graph is opened). # NB: Have it set that if axis is 'adate' then will automatically update # to plot datetime. x_data1 = 'adate' y_data1 = 'graph % diff in output' plot_title1 = 'Photon Output Results' x_axis_title1 = x_data1 y_axis_title1 = y_data1 plot_size_height1 = 450 plot_size_width1 = 800 legend_location = 'bottom_left' hover_tool_fields = ['chamber and electrometer', 'comments'] # Create a list of the plot parameters that will be used as input to a # function later. list_plot_parameters = [ x_data1, y_data1, plot_title1, x_axis_title1, y_axis_title1, plot_size_height1, plot_size_width1, legend_location ] # Define the fields that the legend will be based off. If there is only # one field then put it in both columns. color_column = 'energy' custom_color_boolean = True custom_color_palette = [ '#FF0000', 'black', 'yellow', 'purple', '#008F8F', '#FF00FF', 'white' ] marker_column = 'machinename' custom_marker_boolean = True custom_marker_palette = [ 'circle_x', 'square', 'square_x', 'diamond', 'hex', 'x', 'circle_cross', 'square_cross', 'diamond_cross', 'dash', 'cross', 'inverted_triangle', 'circle', 'triangle', 'asterisk' ] # From the legend defined above give the values that will be pre-ticked when # the plot is opened. NB: Bokeh will throw an error if one of these lists is # empty (i.e. =[]) If only using color or marker then set the color_to plot # and then enter the command: marker_to_plot = color_to_plot. color_to_plot = ['6MV', '10MV'] marker_to_plot = ['TrueBeam B', 'TrueBeam C', 'TrueBeam D'] ############################################################################ #################### CREATE THE DATA FOR THE GRAPH ######################### # Do this in a function so it can be used in an update callback later def Create_df(): # Use the connection passed to the function to read the data into a # dataframe via an SQL query. df = pd.read_sql( 'SELECT [Protocol ID], [Energy], ' \ '[chamber and electrometer], [Chamber factor], ' \ '[Gantry angle], [Temp], [Press], [T/P factor], ' \ '[output], [QI], [Comments], ' \ '[Graph % Diff in output], [Graph % diff in QI] ' \ 'FROM [phcal_Graph] ' \ , conn ) # Delete empty rows where the data is very important to have df = df.dropna(subset=['protocol id'], how='any') df = df.dropna(subset=['energy'], how='any') # The format is complicated for this field but seems to be that the date is # always the first element and the machine is always the last regardless of # how many elements there are. # Seperate on the first '_' df_left = df['protocol id'].str.partition(sep='_') # Seperate on the last '_' df_right = df['protocol id'].str.rpartition(sep='_') # From these sperated dataframes add the appropriate columns back into the # main dataframe. df.loc[:, 'adate'] = df_left[0] df.loc[:, 'machinename'] = df_right[2] # Turn 'adate' into datetime. df.loc[:, 'adate'] = pd.to_datetime(df.loc[:, 'adate'], dayfirst=True) # Drop any rows that aren't related to the Truebeams (ditches the old # uneeded data). Might be possible to put this in the SQL query but # difficult as machinename is embedded in the protocol ID. df = df[df['machinename'].isin( ['TrueBeam B', 'TrueBeam C', 'TrueBeam D', 'TrueBeam F'])] # Drop any columns where there is no data (likely because of the # dropping of the old linacs (e.g. data that used to be collected from # them that is no longer collected for the Truebeams)) df = df.dropna(axis='columns', how='all') return df df = Create_df() # Create a list of the fields using the dataframe. By doing it now before # the extra legend fields are added it's easy to limit what is displayed in # the select widgets. TableFields = (list(df.columns)) ############################################################################ ############################################################################ ############################################################################ ################ CREATE THE DATAFRAME FOR THE TOLERANCES ################### # If you want to add tolerances change the boolean to True and construct the # dataframe in the correct format. tolerance_boolean = True # The format of the dataframe should be the first line being the x_axis # (with some values taken from the main dataframe to get the right # formatting). The subsequent columns are the tolerances [low, high]. # NB: column names should match those from the main dataframe. if tolerance_boolean == True: df_tol1 = pd.DataFrame({ 'adate': [df['adate'].max(), df['adate'].max()], 'output': [98, 102], 'graph % diff in output': [-2, 2] }) # Added a seperate qi tolerance as multiple energes can appear # simultaneously so need an special tolerance function to deal with # this. df_tol1_qi = pd.DataFrame({ 'adate': [df['adate'].max(), df['adate'].max()], 'qi_6MV': [0.64, 0.68], 'qi_6XFFF': [0.61, 0.65], 'qi_10MV': [0.71, 0.75], 'qi_10XFFF': [0.68, 0.72] }) def special_tolerance(color_to_plot, x_data1, y_data1, Sub_df1, df_tol1_qi): energy_list = ['6MV', '6XFFF', '10MV', '10XFFF'] data = {} if (x_data1 != 'adate') or (y_data1 != 'qi'): for x in range(0, len(energy_list)): data.update({ 'x_' + energy_list[x]: [Sub_df1['x'].max(), Sub_df1['x'].max()], 'y_low_' + energy_list[x]: [Sub_df1['y'].max(), Sub_df1['y'].max()], 'y_high_' + energy_list[x]: [Sub_df1['y'].max(), Sub_df1['y'].max()] }) else: # Get a list of the column headers headers1 = df_tol1_qi.columns.values.tolist() # Check if the xdata is what is in the df_tol1 as the x_axis (if not no # point plotting tolerances as all tolerances are vs this column). max_x = Sub_df1['x'].max() + pd.DateOffset(weeks=2) min_x = Sub_df1['x'].min() + pd.DateOffset(weeks=-2) for x in range(0, len(energy_list)): if energy_list[x] in color_to_plot: data.update({ 'x_' + energy_list[x]: [min_x, max_x], 'y_low_' + energy_list[x]: [ df_tol1_qi['qi_' + energy_list[x]][0], df_tol1_qi['qi_' + energy_list[x]][0] ], 'y_high_' + energy_list[x]: [ df_tol1_qi['qi_' + energy_list[x]][1], df_tol1_qi['qi_' + energy_list[x]][1] ] }) else: data.update({ 'x_' + energy_list[x]: [Sub_df1['x'].max(), Sub_df1['x'].max()], 'y_low_' + energy_list[x]: [Sub_df1['y'].max(), Sub_df1['y'].max()], 'y_high_' + energy_list[x]: [Sub_df1['y'].max(), Sub_df1['y'].max()] }) Sub_df1_tol1_qi = pd.DataFrame(data) return Sub_df1_tol1_qi ############################################################################ ############################################################################ ############################################################################ ############################################################################ ''' This is the end of the user input section. If you don't need to make any other changes you can end here. ''' ############################################################################ ################### CREATE THE COLUMNS FOR THE LEGEND ###################### (color_list, color_palette, marker_list, marker_palette, df, add_legend_to_df) = Create_Legend(df, color_column, custom_color_boolean, custom_color_palette, marker_column, custom_marker_boolean, custom_marker_palette) ############################################################################ ############################################################################ ############################################################################ ################## FORMATTING AND CREATING A BASIC PLOT #################### ######### Make Dataset: # Run the Make_Dataset function to create two sub dataframs that the plots # will be made from. Sub_df1 = Make_Dataset(df, color_column, color_to_plot, marker_column, marker_to_plot, x_data1, y_data1) # Make the ColumnDataSource (when making convert dataframe to a dictionary, # which is helpful for the callback). src1 = ColumnDataSource(Sub_df1.to_dict(orient='list')) ######### Make Plot: # Create an empty plot (plot parameters will be applied later in a way that # can be manipulated in the callbacks) p1 = figure() p1.scatter( source=src1, x='x', y='y', fill_alpha=0.4, size=12, # NB: Always use legend_field for this not legend_group as the # former acts on the javascript side but the latter the Python # side. Therefore the former will update automatically. legend_field='legend', marker=factor_mark('marker1', marker_palette, marker_list), color=factor_cmap('color1', color_palette, color_list)) # Run the Define_Plot_Parameters function to set the plot parameters Define_Plot_Parameters(p1, list_plot_parameters) ############################################################################ ############################################################################ ############################################################################ ############################ ADD TOLERANCES ################################ # We defined the tolerances further up and now want to add the correct ones # to the plot. Done in such a way that they are updated with the callbacks # later. if tolerance_boolean == True: Sub_df1_tol1 = Make_Dataset_Tolerance(x_data1, y_data1, Sub_df1, df_tol1) src1_tol = ColumnDataSource(Sub_df1_tol1.to_dict(orient='list')) p1.line(source=src1_tol, x='x', y='y_low', color='firebrick') p1.line(source=src1_tol, x='x', y='y_high', color='firebrick') Sub_df1_tol1_qi = special_tolerance(color_to_plot, x_data1, y_data1, Sub_df1, df_tol1_qi) src1_tol_qi = ColumnDataSource(Sub_df1_tol1_qi.to_dict(orient='list')) p1.line(source=src1_tol_qi, x='x_6MV', y='y_low_6MV', color='yellow') p1.line(source=src1_tol_qi, x='x_6MV', y='y_high_6MV', color='yellow') p1.line(source=src1_tol_qi, x='x_6XFFF', y='y_low_6XFFF', color='mediumorchid') p1.line(source=src1_tol_qi, x='x_6XFFF', y='y_high_6XFFF', color='mediumorchid') p1.line(source=src1_tol_qi, x='x_10MV', y='y_low_10MV', color='firebrick') p1.line(source=src1_tol_qi, x='x_10MV', y='y_high_10MV', color='firebrick') p1.line(source=src1_tol_qi, x='x_10XFFF', y='y_low_10XFFF', color='black') p1.line(source=src1_tol_qi, x='x_10XFFF', y='y_high_10XFFF', color='black') ############################################################################ ############################################################################ ############################################################################ ################## ADD MORE COMPLEX TOOLS TO THE PLOT ###################### ######## 1) # Create a hover tool and add it to the plot hover1 = HoverTool() if len(hover_tool_fields) < 11: kwargs = {} i = 0 for x in hover_tool_fields: i = i + 1 kwargs['Field' + str(i)] = x else: kwargs = {} msgbox('Too many fields selected to display on HoverTool ' \ '(Max = 10). Please reduce number of fields selected') Update_HoverTool(hover1, x_data1, y_data1, **kwargs) p1.add_tools(hover1) ############################################################################ ############################################################################ ############################################################################ ################# CREATE WIDGETS TO BE ADDED TO THE PLOT ################### ######## 1) # This select funtion will be used to create dropdown lists to change the # data plotted on the x/y-axis. select_xaxis, select_yaxis = Create_Select_Axis(TableFields, x_axis_title1, y_axis_title1) ######## 2) # This select widget will be used to create dropdown lists to change the # legend position. select_legend = Create_Select_Legend(legend_location) ######## 3) # These checkbox widgets will be used to create a tool to select the machine # and energy that are being plotted. checkbox_color, checkbox_marker = Create_Checkbox_Legend( df, color_column, color_to_plot, marker_column, marker_to_plot) ######## 4) # These checkbox widgets will be used to create a tool to select the machine # and energy that are being plotted. checkbox_hovertool = Create_Checkbox_HoverTool(TableFields, hover_tool_fields) ######## 5) # Make an 'Update Button' to requery the database and get up to date data. update_button = Button(label='Update', button_type='success') ######## 6) # Make a Range Button range_button = Button(label='Range', button_type='primary') ######## 7) # Make some titles for the checkboxes color_title = Div(text='<b>Energy Choice</b>') marker_title = Div(text='<b>Machine Choice</b>') hover_title = Div(text='<b>Hovertool Fields</b>') ############################################################################ ############################################################################ ############################################################################ ############################ CREATE A LAYOUT ############################### # Create a layout where the widgets will be added and any scaling applied. if color_column == marker_column: layout_checkbox = column( [color_title, checkbox_color, hover_title, checkbox_hovertool]) else: layout_checkbox = column([ color_title, checkbox_color, marker_title, checkbox_marker, hover_title, checkbox_hovertool ]) button_row = row([update_button, range_button]) layout_plots = column( [button_row, select_xaxis, select_yaxis, select_legend, p1]) tab_layout = row([layout_plots, layout_checkbox]) ############################################################################ ############################################################################ ############################################################################ ####################### CREATE CALLBACK FUNCTIONS ########################## # Create a big callback that does most stuff def callback(attr, old, new): # Want to acquire the current values of all of the checkboxes and select # widgets to provide as inputs for the re-plot. color_to_plot = [ checkbox_color.labels[i] for i in checkbox_color.active ] if color_column != marker_column: marker_to_plot = [ checkbox_marker.labels[i] for i in checkbox_marker.active ] else: marker_to_plot = color_to_plot hovertool_to_plot = [ checkbox_hovertool.labels[i] for i in checkbox_hovertool.active ] plot1_xdata_to_plot = select_xaxis.value plot1_ydata_to_plot = select_yaxis.value legend_location = select_legend.value # Set the new axis titles x_axis_title1 = plot1_xdata_to_plot y_axis_title1 = plot1_ydata_to_plot # Use the pre-defined Make_Dataset function with these new inputs to # create new versions of the sub dataframes. Sub_df1 = Make_Dataset(df, color_column, color_to_plot, marker_column, marker_to_plot, plot1_xdata_to_plot, plot1_ydata_to_plot) # Use the pre-defined Define_Plot_Parameters function with these new # inputs to update the plot. Define_Plot_Parameters(p1, [ plot1_xdata_to_plot, plot1_ydata_to_plot, plot_title1, x_axis_title1, y_axis_title1, plot_size_height1, plot_size_width1, legend_location ]) # Update the hovertool if len(hovertool_to_plot) < 11: kwargs = {} i = 0 for x in hovertool_to_plot: i = i + 1 kwargs['Field' + str(i)] = x else: kwargs = {} msgbox('Too many fields selected to display on HoverTool ' \ '(Max = 10). Please reduce number of fields selected') Update_HoverTool(hover1, plot1_xdata_to_plot, plot1_ydata_to_plot, **kwargs) print(hover1.tooltips) print(p1.hover.tooltips) print(hover1) print(p1.hover) # Use the pre-defined Make_Dataset_Tolerance function with these new # inputs to update the tolerances. if tolerance_boolean == True: Sub_df1_tol1 = Make_Dataset_Tolerance(plot1_xdata_to_plot, plot1_ydata_to_plot, Sub_df1, df_tol1) Sub_df1_tol1_qi = special_tolerance(color_to_plot, plot1_xdata_to_plot, plot1_ydata_to_plot, Sub_df1, df_tol1_qi) # Update the ColumnDataSources. src1.data = Sub_df1.to_dict(orient='list') if tolerance_boolean == True: src1_tol.data = Sub_df1_tol1.to_dict(orient='list') src1_tol_qi.data = Sub_df1_tol1_qi.to_dict(orient='list') return select_xaxis.on_change('value', callback) select_yaxis.on_change('value', callback) select_legend.on_change('value', callback) checkbox_color.on_change('active', callback) checkbox_marker.on_change('active', callback) checkbox_hovertool.on_change('active', callback) # Callback for the Update Button def callback_update(): # Make a new version of the dataframe using the original Create_df # function that connects to the database. df = Create_df() df = add_legend_to_df(df) color_to_plot = [ checkbox_color.labels[i] for i in checkbox_color.active ] if color_column != marker_column: marker_to_plot = [ checkbox_marker.labels[i] for i in checkbox_marker.active ] else: marker_to_plot = color_to_plot hovertool_to_plot = [ checkbox_hovertool.labels[i] for i in checkbox_hovertool.active ] plot1_xdata_to_plot = select_xaxis.value plot1_ydata_to_plot = select_yaxis.value x_axis_title1 = plot1_xdata_to_plot y_axis_title1 = plot1_ydata_to_plot legend_location = select_legend.value Sub_df1 = Make_Dataset(df, color_column, color_to_plot, marker_column, marker_to_plot, plot1_xdata_to_plot, plot1_ydata_to_plot) Define_Plot_Parameters(p1, [ plot1_xdata_to_plot, plot1_ydata_to_plot, plot_title1, x_axis_title1, y_axis_title1, plot_size_height1, plot_size_width1, legend_location ]) if len(hovertool_to_plot) < 11: kwargs = {} i = 0 for x in hovertool_to_plot: i = i + 1 kwargs['Field' + str(i)] = x else: kwargs = {} msgbox('Too many fields selected to display on HoverTool ' \ '(Max = 10). Please reduce number of fields selected') Update_HoverTool(hover1, plot1_xdata_to_plot, plot1_ydata_to_plot, **kwargs) if tolerance_boolean == True: Sub_df1_tol1 = Make_Dataset_Tolerance(plot1_xdata_to_plot, plot1_ydata_to_plot, Sub_df1, df_tol1) Sub_df1_tol1_qi = special_tolerance(color_to_plot, plot1_xdata_to_plot, plot1_ydata_to_plot, Sub_df1, df_tol1_qi) src1_tol.data = Sub_df1_tol1.to_dict(orient='list') src1_tol_qi.data = Sub_df1_tol1_qi.to_dict(orient='list') src1.data = Sub_df1.to_dict(orient='list') return update_button.on_click(callback_update) # Callback for the Range Button def callback_range(): color_to_plot = [ checkbox_color.labels[i] for i in checkbox_color.active ] if color_column != marker_column: marker_to_plot = [ checkbox_marker.labels[i] for i in checkbox_marker.active ] else: marker_to_plot = color_to_plot plot1_xdata_to_plot = select_xaxis.value plot1_ydata_to_plot = select_yaxis.value # Use the pre-defined Make_Dataset function with these new inputs to # create new versions of the sub dataframes. Sub_df1 = Make_Dataset(df, color_column, color_to_plot, marker_column, marker_to_plot, plot1_xdata_to_plot, plot1_ydata_to_plot) if (plot1_xdata_to_plot == 'adate') and ( (plot1_ydata_to_plot == 'graph % diff in output') or (plot1_ydata_to_plot == 'output') or plot1_ydata_to_plot == 'qi'): p1.x_range.start = Sub_df1['x'].max() - timedelta(weeks=53) p1.x_range.end = Sub_df1['x'].max() + timedelta(weeks=2) if plot1_ydata_to_plot == 'output': p1.y_range.start = 97 p1.y_range.end = 103 elif plot1_ydata_to_plot == 'graph % diff in output': p1.y_range.start = -3 p1.y_range.end = 3 elif plot1_ydata_to_plot == 'qi': p1.y_range.start = 0.55 p1.y_range.end = 0.8 return range_button.on_click(callback_range) ############################################################################ ############################################################################ ############################################################################ ####################### RETURN TO THE MAIN SCRIPT ########################## return Panel(child=tab_layout, title='Photon Output')
from bokeh.io import output_file, show from bokeh.layouts import column from bokeh.plotting import figure output_file("layout.html") x = list(range(11)) y0 = x y1 = [10 - i for i in x] y2 = [abs(i - 5) for i in x] # create three plots s1 = figure(width=250, height=250, background_fill_color="#fafafa") s1.circle(x, y0, size=12, color="#53777a", alpha=0.8) s2 = figure(width=250, height=250, background_fill_color="#fafafa") s2.triangle(x, y1, size=12, color="#c02942", alpha=0.8) s3 = figure(width=250, height=250, background_fill_color="#fafafa") s3.square(x, y2, size=12, color="#d95b43", alpha=0.8) # put the results in a column and show show(column(s1, s2, s3))
from bokeh.io import output_file, show from bokeh.plotting import figure output_file("stacked.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ["2015", "2016", "2017"] colors = ["#c9d9d3", "#718dbf", "#e84d60"] data = { 'fruits': fruits, '2015': [2, 1, 4, 3, 2, 4], '2016': [5, 3, 4, 2, 4, 6], '2017': [3, 2, 4, 4, 5, 3] } p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year", toolbar_location=None, tools="") p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data, legend_label=years) p.y_range.start = 0 p.x_range.range_padding = 0.1
def create_cws_map(df, suffix): """Reads in a data-frame and exports a html file, containing a bokeh map, placed within the 'maps' folder. Parameters ---------- df : dataframe A dataframe that must contain the following columns: - geometry - p_id - lon - lat - ta_int suffix : str A string that will be appended to the title of the plots as well as the html file-names. """ tile_provider = get_provider( "CARTODBPOSITRON_RETINA" ) # More Providers https://docs.bokeh.org/en/latest/docs/reference/tile_providers.html # Range bounds supplied in web mercator coordinates p = figure( x_range=(825000, 833000), y_range=(5933000, 5935000), x_axis_type="mercator", y_axis_type="mercator", # Changes axis to a more legible input x_axis_label="Longitude", y_axis_label="Latitude", sizing_mode="stretch_both") p.add_tile(tile_provider) # Filter point sto be added by color p = filter_points_by_color(df, p) # Add hover tools as a means for interactivity my_hover = HoverTool( ) # https://automating-gis-processes.github.io/2016/Lesson5-interactive-map-bokeh.html#adding-interactivity-to-the-map # Specify what parameters should be displayed when hovering my_hover.tooltips = [('Id', '@p_id'), ('Temperature [C]', '@ta_int'), ('Longitude', '@lon'), ('Latitude', '@lat')] p.add_tools(my_hover) # Creating divs to serve as additional information div_title = Div(align="center", text="<h1>Citizen Weather Stations: " + suffix + ":00</h1>", sizing_mode="stretch_both") div_subtitle = Div( align="center", text= "Blue: Below 22 °C. <br> Orange: Between 22 °C and 28 °C. <br> Red: Above 28 °C.", sizing_mode="stretch_both") # Arrange all the bokeh elements in a layout layout_plot = layout([[div_title], [div_subtitle], [p]]) # Specify output location and name output_file("../maps/Bern-CWS-Map_" + suffix + ".html") # Shows the result in the default browser and saves the file show(layout_plot)
# Bokeh libraries from bokeh.io import output_file from bokeh.layouts import gridplot # Output to file output_file( "east-west-top-2-gridplot.html", title="Conference Top 2 Teams Wins Race" ) # Reduce the width of both figures east_fig.plot_width = west_fig.plot_width = 300 # noqa # Edit the titles east_fig.title.text = "Eastern Conference" # noqa west_fig.title.text = "Western Conference" # noqa # Configure the gridplot east_west_gridplot = gridplot( [[west_fig, east_fig]], toolbar_location="right" # noqa ) # Plot the two visualizations in a horizontal configuration show(east_west_gridplot) # noqa
import numpy as np from bokeh.layouts import widgetbox, column, row from bokeh.models import Slider import bokeh.plotting as plt from bokeh.models import HoverTool, ColumnDataSource, Select, Slider, WheelZoomTool, Range1d from bokeh.io import output_notebook, show, push_notebook, output_file, curdoc output_file("test.html") def radii(gamma, x0, y0, r): '''calculates the two intersections of a line from the origin with the circle defining the window''' r1 = np.cos(gamma) * x0 + np.sin(gamma) * y0 + np.sqrt( (np.cos(gamma) * x0 + np.sin(gamma) * y0)**2 - (x0**2 + y0**2 - r**2)) r2 = np.cos(gamma) * x0 + np.sin(gamma) * y0 - np.sqrt( (np.cos(gamma) * x0 + np.sin(gamma) * y0)**2 - (x0**2 + y0**2 - r**2)) return (r1, r2) def excentricity(beta, e_window, e_sample=[0, -46]): '''calculates the excentricity of the circle defining the window for different top flange rotations''' x0 = np.cos(beta) * e_window - e_sample[0] y0 = np.sin(beta) * e_window - e_sample[1] return x0, y0 def phi(r, h): ''' Returns the scatter angle measured from the vertical of r with height above the sample,h. ''' return np.arctan(r / h)
# Circles, Squares, Triangles # Rectangles, lines, Wedges # With properties attached to data # Coordinates (x, y) # Size, Color, Transparency # Import output_file and show from bokeh.io from bokeh.io import output_file, show # Import figure from bokeh.plotting from bokeh.plotting import figure plot = figure(plot_width = 400, tools='pan, box_zoom') plot.circle([1,2,3,4,5],[8,6,5,2,3]) output_file('Bokeh_Output/circle.html') # show(plot) # Glyph Properties # List, Arrays, Sequences of Values # Single Fixed Values plot = figure() plot.circle(x=10, y=[2,5,8,12], size=[10,20,30,40]) output_file('Bokeh_Output/v_circle.html') show(plot) # A simple scatter plot
def plot_map(perf_map, res, title='performance map', colors=BLUE_COLORS, show=True, scale='default'): ps = list(perf_map.values()) #p_min, p_max = np.min(ps), np.max(ps) p_min, p_max = 0.17, 0.45 if scale == 'log': c_min, c_max = -math.log(-p_min + EPSILON), -math.log(-p_max + EPSILON) else: c_min, c_max = p_min, p_max img = np.zeros((res, res), dtype=np.uint32) view = img.view(dtype=np.uint8).reshape(img.shape + (4, )) for (i, j), p in perf_map.items(): if scale == 'log': p = -math.log(-p + EPSILON) c_idx = int(np.floor( (len(colors) - 1) * (p - c_min) / (c_max - c_min))) r, g, b = colors[c_idx] view[j, i, 0] = r view[j, i, 1] = g view[j, i, 2] = b view[j, i, 3] = 255 #plot = bkp.figure(width=SIZE, height=SIZE, x_range=(-0.7, 0.7), y_range=(-0.7, 0.7), title=title, tools = "pan,box_zoom,reset,save") plot = bkp.figure(width=SIZE, height=SIZE, x_range=(0, 1), y_range=(0, 1), title=title, tools="pan,box_zoom,reset,save") plot.title.text_font_size = '12pt' plot.yaxis.axis_label = "SS(x)" plot.xaxis.axis_label = "BS(x)" #plot.image_rgba([img], x=[-0.7], y=[-0.7], dh=[1.4], dw=[1.4]) plot.image_rgba([img], x=[0], y=[0], dh=[1], dw=[1]) if scale == 'log': cbar = colorbar(colors, inversed=True) cb_plot = bkp.figure(width=100, height=SIZE, x_range=(0, 1.0), y_axis_type="log", y_range=(-p_max, -p_min)) cb_plot.image_rgba([cbar], x=[0.0], y=[-p_max], dw=[1.0], dh=[p_max - p_min]) else: cbar = colorbar(colors) cb_plot = bkp.figure(title="DR(x)", width=100, height=SIZE, x_range=(0, 1.0), y_range=(p_min, p_max)) cb_plot.image_rgba([cbar], x=[0.0], y=[p_min], dw=[1.0], dh=[p_max - p_min]) cb_plot.min_border_right = 25 cb_plot.xgrid.grid_line_color = None cb_plot.xaxis.minor_tick_line_color = None cb_plot.xaxis.major_tick_line_color = None cb_plot.xaxis.axis_line_color = None cb_plot.xaxis[0].formatter = PrintfTickFormatter(format="") if scale == 'log': cb_plot.yaxis.formatter = PrintfTickFormatter(format="-%1.0e") if show: output_file("foo.html") bkp.show(bkp.gridplot([[plot, cb_plot]])) return [plot, cb_plot]
def plot_location_cluster(df_clusters, to_drop = 5, path_to_file='', file_name=''): """ Create a fancy html visualization with bokeh. Paramaters: df_clusters: GeoDataFrame containing the shape files, municipality codes and cluster labels to_drop: minimum number of municipalities in a cluster to color. If a cluster contains fewer municipalities, their appear white. path_to_file: str, path to the results folder file_name: str, results name file """ # expand multipolygons into multiple lines shp_expanded = df_clusters.set_index(['PRO_COM'])['geometry'].apply(pd.Series).stack().reset_index() shp_expanded.rename(columns = {0: 'geometry'}, inplace = True) df_exp = shp_expanded.merge(df_clusters.drop(columns = 'geometry'), on = 'PRO_COM', how = 'left') # drop municipalities (i.e., make them white in the plot) df_exp['labels_count'] = df_exp.groupby('labels')['labels'].transform('count') df_exp.loc[df_exp['labels_count'] < to_drop, 'labels'] = 100000 # renumber the clusters values = np.arange(1, df_exp['labels'].unique().size+1) keys = sorted(df_exp['labels'].unique()) df_exp['labels'] = df_exp['labels'].map(dict(zip(keys, values))) # Get lat lon from geometry to plot df_toplot = df_exp.drop('geometry', axis=1).copy() df_toplot['x'] = df_exp.apply(getGeometryCoords, geom='geometry', coord_type='x', shape_type='polygon', axis=1) df_toplot['y'] = df_exp.apply(getGeometryCoords, geom='geometry', coord_type='y', shape_type='polygon', axis=1) # create colormap cs = create_funky_cmap(len(list(map(str, sorted(df_toplot['labels'].unique()))))-1) colors = [] for c in cs: r, g, b = c colors.append(rgb2hex(r, g, b)) colors.append("#ffffff") # make last cluster white # remove non unicode characters df_toplot['COMUNE'] = df_toplot['COMUNE'].apply(unidecode.unidecode) # Make LocationClusterMap mapper = CategoricalColorMapper(palette=colors,factors=list(map(str, sorted(df_toplot['labels'].unique())))) source = ColumnDataSource(data=dict( x=df_toplot['x'], y=df_toplot['y'], name=df_toplot['COMUNE'], similar=df_toplot['similar'], label=df_toplot['labels'].astype(str))) p = figure( x_axis_location=None, y_axis_location=None, plot_width=800, plot_height=700) p.grid.grid_line_color = None p.outline_line_color = None p.title.align = "center" p.title.text_font_size="40px" p.patches('x', 'y', source=source, fill_color=transform('label', mapper), fill_alpha=0.8, line_color="lightgray", line_width=0.3) # color_bar = ColorBar(color_mapper=mapper, ticker=BasicTicker(), # label_standoff=12, border_line_color=None, location=(0,0)) # p.add_layout(color_bar, 'right') #Add tools hover= HoverTool(tooltips = [ ("Comune","@name"), ("Most similar (ordered)","@similar"), ("Cluster number:", "@label") ]) p.add_tools(PanTool(), WheelZoomTool(), hover) if not os.path.exists(path_to_file): os.makedirs(path_to_file) output_file(path_to_file+file_name) save(p)
color="#386CB0", fill_color=None, line_width=2) children.append(p) p = figure(title="Marker: circle_cross") p.scatter(x, y, marker="circle_cross", size=sizes, color="#FB8072", fill_color=None, line_width=2) children.append(p) # simplify theme by turning off axes and gridlines curdoc().theme = Theme( json={"attrs": { "Axis": { "visible": False }, "Grid": { "visible": False } }}) output_file("glyphs.html", title="glyphs.py example") show(gridplot(children, ncols=4, plot_width=200, plot_height=200)) # open a browser