我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用bokeh.plotting.figure()。
def plot(a): panels = a.rotated_panel_positions x = [x['x'] for x in panels] y = [x['y'] for x in panels] ids = [x['panelId'] for x in panels] angles = [x['o'] for x in panels] pad_x = (max(x) - min(x)) * .1 pad_y = (max(y) - min(y)) * .1 output_file('plot.html') plot = figure(x_range=(min(x) - pad_x, max(x) + pad_x), y_range=(min(y) - pad_y, max(y) + pad_y)) source = ColumnDataSource(dict(x=x, y=y, text=ids)) plot.triangle(x, y, angle=angles, angle_units='deg', size=70, color='#cccccc', fill_color=None, line_width=4) glyph = Text(x='x', y='y', text='text', angle=0, text_align='center', text_color='#FF0000') plot.add_glyph(source, glyph) show(plot)
def plot_csv(stock_data, symbol): """ params: - stock_data(list) : list of dict objects containing stock data - name(str) : output file name specified by `-output` param. """ try: df = pd.read_csv('{}.csv'.format(symbol)) except: write_to_csv(stock_data, symbol) df = pd.read_csv('{}.csv'.format(symbol)) p1 = figure(x_axis_type="datetime", title="Stock Closing Price") p1.grid.grid_line_alpha = 0.3 p1.xaxis.axis_label = 'Date' p1.yaxis.axis_label = 'Price' p1.line(datetime(list(df['date'])), list(df['close']), color='#A6CEE3', legend=symbol) output_file("{}.html".format(symbol), title="Stock Closing Prices") show(p1) # open a browser
def tsne_cluster_cuisine(df,sublist): lenlist=[0] df_sub = df[df['cuisine']==sublist[0]] lenlist.append(df_sub.shape[0]) for cuisine in sublist[1:]: temp = df[df['cuisine']==cuisine] df_sub = pd.concat([df_sub, temp],axis=0,ignore_index=True) lenlist.append(df_sub.shape[0]) df_X = df_sub.drop(['cuisine','recipeName'],axis=1) print df_X.shape, lenlist dist = squareform(pdist(df_X, metric='cosine')) tsne = TSNE(metric='precomputed').fit_transform(dist) palette = sns.color_palette("hls", len(sublist)) plt.figure(figsize=(10,10)) for i,cuisine in enumerate(sublist): plt.scatter(tsne[lenlist[i]:lenlist[i+1],0],\ tsne[lenlist[i]:lenlist[i+1],1],c=palette[i],label=sublist[i]) plt.legend() #interactive plot with boken; set up for four categories, with color palette; pass in df for either ingredient or flavor
def make_commment_bokeh(data): if data: temps = "".join(data).replace(" ", "").replace("\r\n", "") values = re.findall(r'(\d+)', temps) c_values = [int(value) for value in values] c_keys = re.findall('[\u4e00-\u9fa5]+', temps) # s = pd.Series(c_values, index=c_keys, name='???') s = s[3:6] s_sum = s.sum() s = s.apply(lambda x: x / s_sum * 100) factors = list(s.index) x = s.values dot = figure(title="???(??:%)", tools=TOOLS, toolbar_location=None, y_range=factors, x_range=[0, 100],width=400, height=400) dot.segment(0, factors, x, factors, line_width=2, line_color="green", ) dot.circle(x, factors, size=15, fill_color="orange", line_color="green", line_width=3, ) script, div = components(dot, CDN) return [script,div] else: return [0,file_hepler.get_image_path("no_good_comments.png")]
def make_hot_bokeh(data): from bokeh.models import BoxAnnotation if data: data = data.split(",") dt1 = datetime.datetime.now() temp = list(set(data)) sub_dates = [(dt1 - datetime.datetime.strptime(dt, '%Y-%m-%d')).days for dt in temp] s = pd.Series(sub_dates, [datetime.datetime.strptime(dt, '%Y-%m-%d') for dt in temp]) s = s.sort_index(ascending=False) p = figure(x_axis_type="datetime", tools="",title="??", x_axis_label='??', y_axis_label='??',width=400, height=400) p.line(s.index,s.values, legend="??????", line_width=2) script, div = components(p, CDN) return [script, div] else: return [0,file_hepler.get_image_path("no_hot.png")]
def update_plot(attr, old, new): # Assign the value of the slider: yr yr = slider.value # Set new_data new_data = { 'x' : data.loc[yr].fertility, 'y' : data.loc[yr].life, 'country' : data.loc[yr].Country, 'pop' : (data.loc[yr].population / 20000000) + 2, 'region' : data.loc[yr].region, } # Assign new_data to: source.data source.data = new_data # Add title to figure: plot.title.text plot.title.text = 'Gapminder data for %d' % yr # Make a slider object: slider
def plot_waveforms(waveforms, figTitle=''): channels = waveforms.keys() # plot plots = [] for (ct, chan) in enumerate(channels): fig = bk.figure(title=figTitle + repr(chan), plot_width=800, plot_height=350, y_range=[-1.05, 1.05], x_axis_label=u'Time (?s)') fig.background_fill_color = config.plotBackground if config.gridColor: fig.xgrid.grid_line_color = config.gridColor fig.ygrid.grid_line_color = config.gridColor waveformToPlot = waveforms[chan] xpts = np.linspace(0, len(waveformToPlot) / chan.phys_chan.sampling_rate / 1e-6, len(waveformToPlot)) fig.line(xpts, np.real(waveformToPlot), color='red') fig.line(xpts, np.imag(waveformToPlot), color='blue') plots.append(fig) bk.show(column(*plots))
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) self.plot = figure( x_axis_type="datetime", plot_width=400, plot_height=300, tools='', toolbar_location=None) vbar = self.plot.vbar( x='date', top='prcp', width=1, color='#fdae61', source=self.source) hover_tool = HoverTool(tooltips=[ ('Value', '$y'), ('Date', '@date_readable'), ], renderers=[vbar]) self.plot.tools.append(hover_tool) self.plot.xaxis.axis_label = None self.plot.yaxis.axis_label = None self.plot.axis.axis_label_text_font_style = 'bold' self.plot.x_range = DataRange1d(range_padding=0.0) self.plot.grid.grid_line_alpha = 0.3 self.title = Paragraph(text=TITLE) return column(self.title, self.plot)
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) self.plot = figure( x_axis_type="datetime", plot_width=600, plot_height=300, tools='', toolbar_location=None) self.plot.quad( top='max_temp', bottom='min_temp', left='left', right='right', color=Blues4[2], source=self.source, legend='Magnitude') line = self.plot.line( x='date', y='avg_temp', line_width=3, color=Blues4[1], source=self.source, legend='Average') hover_tool = HoverTool(tooltips=[ ('Value', '$y'), ('Date', '@date_readable'), ], renderers=[line]) self.plot.tools.append(hover_tool) self.plot.xaxis.axis_label = None self.plot.yaxis.axis_label = None self.plot.axis.axis_label_text_font_style = 'bold' self.plot.x_range = DataRange1d(range_padding=0.0) self.plot.grid.grid_line_alpha = 0.3 self.title = Paragraph(text=TITLE) return column(self.title, self.plot)
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) palette = all_palettes['Set2'][6] hover_tool = HoverTool(tooltips=[ ("Value", "$y"), ("Year", "@year"), ]) self.plot = figure( plot_width=600, plot_height=300, tools=[hover_tool], toolbar_location=None) columns = { 'pm10': 'PM10 Mass (µg/m³)', 'pm25_frm': 'PM2.5 FRM (µg/m³)', 'pm25_nonfrm': 'PM2.5 non FRM (µg/m³)', 'lead': 'Lead (¹/??? µg/m³)', } for i, (code, label) in enumerate(columns.items()): self.plot.line( x='year', y=code, source=self.source, line_width=3, line_alpha=0.6, line_color=palette[i], legend=label) self.title = Paragraph(text=TITLE) return column(self.title, self.plot) # [END make_plot]
def _line_scatter(h1, kind, show=True, **kwargs): """Line or scatter plot. The common functionality (the plots differ only in method called). """ density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) size = kwargs.pop("size", 8) p = kwargs.pop("figure", _create_figure(h1)) data = get_data(h1, cumulative=cumulative, density=density) plot_data = { "x" : h1.bin_centers, "y" : data } if kind == "line": p.line(plot_data['x'], plot_data['y']) elif kind == "scatter": p.scatter(plot_data['x'], plot_data['y'], size=size) if show: bokeh_show(p) return p
def weight(repo, compare_repo=None): repo_saving, compare_saving, compare_name = _combine_repo(repo, compare_repo, 'trainable_params') def show(attr, old, new): layername = new g = [[]] for i, (wtname, wt) in enumerate(repo_saving[layername].items()): if wt.ndim == 4: wt.transpose(0, 2, 1, 3) wt.reshape([wt.shape[:2], wt.shape[2:]]) p = plt.figure(plot_width=100, plot_height=100, title=wtname, tools=[]) if wt.ndim == 1: p.line(range(wt.shape[0]), wt, line_width=2, color='black') else: p.image([wt], [0], [0], [p.x_range[-1]], [p.y_range[-1]]) g[-1].append(p) if (i + 1) % 5 == 0: g.append([]) v = lyt.gridplot(g, toolbar_location="below", merge_tools=True) plt.output_file('./weightplot.html', title='WeightPlot') select = models.widgets.Select(title="Layer:", value=repo_saving.keys()[0], options=repo_saving.keys()) select.on_change("value", show) plt.save(lyt.widgetbox(select))
def plot_histogram(values, **kwargs): """ Convenience function. Plots a histogram of flat 1D data. :param tmodel: :param solution: :return: """ hist, edges = np.histogram(values, **kwargs) p1 = figure(tools="save") p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#033649") return p1
def plot_ccf(self, name, T, x_range=None): # Load the ccf from the HDF5 file. logging.debug('Plotting ccf name {}'.format(name)) observation = self.inst_date i = observation.find('/') instrument = observation[:i] vel, corr = self._ccf_interface.load_ccf(instrument, name) # Now, plot p = figure( title='{} K'.format(T), x_range=x_range, plot_width=600, plot_height=400, title_text_font_size="10pt", tools="pan,wheel_zoom,box_select,reset,save" ) p.line(vel, corr, line_width=2) p.xaxis[0].axis_label = 'Velocity (km/s)' p.yaxis[0].axis_label = 'CCF Power' return p
def run(self): print("In thread.run") self.p = figure(plot_height=500, tools=TOOLS, y_axis_location='left', title=self.title) self.p.x_range.follow = "end" self.p.xaxis.axis_label = "Timestamp" self.p.x_range.follow_interval = 100 self.p.x_range.range_padding = 0 self.p.line(x="timestamp", y="value", color="blue", source=self.source) self.p.circle(x="timestamp", y="value", color="red", source=self.source) self.session = push_session(curdoc()) curdoc().add_periodic_callback(self.update, 100) #period in ms self.session.show(column(self.p)) curdoc().title = 'Sensor' self.session.loop_until_closed() # def register(self, d, sourceq): # source = ColumnDataSource(dict(d)) # self.p.line(x=d[0], y=d[1], color="orange", source=source) # curdoc().add_periodic_callback(self.update, 100) #period in ms
def modify_doc(doc): df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource(data=data).data slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) doc.add_root(column(slider, plot)) # doc.theme = Theme(filename="theme.yaml")
def sample(): # create the chart p = figure(plot_width=400, plot_height=400) # add a line renderer p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2) # grab the static resources js_resources = INLINE.render_js() css_resources = INLINE.render_css() # generate javascript and the actual chart via components() script, div = components(p) # render template return render_template( 'index.html', plot_script=script, plot_div=div, js_resources=js_resources, css_resources=css_resources, )
def chart(): # create chart p = figure(plot_width=1000, plot_height=400, x_axis_type='datetime') # add a line renderer x = [] y = [] all_data = get_data() # refactor for value in all_data: date = datetime.datetime.fromtimestamp(value[0]) x.append(date) y.append(value[1]) p.line(x, y, line_width=2) # create static files js_resources = INLINE.render_js() css_resources = INLINE.render_css() script, div = components(p) # render template return render_template( 'chart.html', plot_script=script, plot_div=div, js_resources=js_resources, css_resources=css_resources )
def get_states_plot(): source = AjaxDataSource( data={'STATE': [], 'STNAME': [], 'STUSAB': [], 'TOT_POP': [], 'TOT_MALE': [], 'TOT_FEMALE': []}, data_url='/api/states/', mode='replace', method='GET') hover = HoverTool( tooltips=[ ("State", "@STNAME"), ("Population", "@TOT_POP"), ("Female Population", "@TOT_FEMALE"), ("Male Population", "@TOT_MALE"), ] ) plot = figure(title='Population by State', plot_width=1200, plot_height=500, x_range=FactorRange(factors=get_state_abbreviations()), y_range=(0, 40000000), tools=[hover, 'tap','box_zoom','wheel_zoom','save','reset']) plot.toolbar.active_tap = 'auto' plot.xaxis.axis_label = 'State' plot.yaxis.axis_label = 'Population' plot.yaxis.formatter = NumeralTickFormatter(format="0a") plot.sizing_mode = 'scale_width' plot.vbar(bottom=0, top='TOT_POP', x='STUSAB', legend=None, width=0.5, source=source) url = "/counties/@STATE/" taptool = plot.select(type=TapTool) taptool.callback = OpenURL(url=url) return plot
def index(request): if request.method == "GET" : return render_to_response('bokeh/index.html') elif request.method == "POST" : domain = request.POST['domain'].split() eqn = request.POST['equation'] domain = range( int(domain[0]), int(domain[1]) ) y = [ eval(eqn) for x in domain ] title = 'y = ' + eqn plot = figure(title= title , x_axis_label= 'X-Axis', y_axis_label= 'Y- Axis', plot_width =400, plot_height =400) plot.line(domain, y, legend= 'f(x)', line_width = 2) script, div = components(plot) return render_to_response( 'bokeh/index.html', {'script' : script , 'div' : div} ) else: pass
def plot_scatter_charts(data, file_name): scatters = [] for lang, values in data.items(): s = figure(width=300, plot_height=300, title=lang) s.yaxis.formatter = NumeralTickFormatter(format="0.0a") s.circle(values[0], values[1], size=10, color="navy", alpha=0.5) x = np.linspace(1, 100, 10) # noinspection PyTupleAssignmentBalance m, b = np.polyfit(values[0], values[1], 1) y = m * x + b corr_coef = round(pearsonr(values[0], values[1])[0], 1) s.line(x, y, legend=f'PCC = {corr_coef}') scatters.append(s) split_scatters = split(scatters, 3) p = gridplot(split_scatters) output_file(file_name) show(p)
def bokeh_scatter_plot(tsne_df): output_file("results\\Anime_similarity.html") # Prep plot plot_anime_sim = bp.figure(plot_width=700, plot_height=600, title="Anime Similarity plotted with tSNE", tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave,tap", x_axis_type=None, y_axis_type=None, toolbar_location="below", toolbar_sticky=False) # Plotting the anime data plot_anime_sim.scatter(x='x', y='y', source=tsne_df) # Handle hover tools hover = plot_anime_sim.select(dict(type=HoverTool)) hover.tooltips={"Anime":"@anime_name [@rating]"} # Add ability to click links: url = "http://www.myanimelist.net/anime/@anime_id" taptool = plot_anime_sim.select(type=TapTool) taptool.callback = OpenURL(url=url) # Show the file: show(plot_anime_sim) script, div = components(plot_anime_sim) with open("results\\sim_script.js", "w") as text_file: text_file.write(script[37:-10]) with open("results\\sim_html.html", "w") as text_file: text_file.write(div) #%% Main code:
def getPlot(title): p = figure(plot_height=200, plot_width=400, min_border=40, toolbar_location=None, title=title) p.background_fill_color = "#515052" # Background color p.title.text_color = "#333138" # Title color p.title.text_font = "helvetica" # Title font p.x_range.follow = "end" # Only show most recent window of data p.x_range.follow_interval = 60 # Moving window size p.xaxis.major_tick_line_color = None # Turn off x-axis major ticks p.xaxis.minor_tick_line_color = None # Turn off x-axis minor ticks p.yaxis.major_tick_line_color = None # Turn off y-axis major ticks p.yaxis.minor_tick_line_color = None # Turn off y-axis minor ticks p.xgrid.grid_line_alpha = 0 # Hide X-Axis grid p.ygrid.grid_line_alpha = 0 # Hide Y-Axis grid p.xaxis.major_label_text_color = "#333138" # X-Axis color p.yaxis.major_label_text_color = "#333138" # Y-Axis color p.extra_y_ranges = {"sentiment": Range1d(start=-1, end=1)} p.add_layout(LinearAxis(y_range_name="sentiment", major_tick_line_color = None, minor_tick_line_color = None), 'right') return p
def graph_bgp(label_dict, redundancy_counts, x_ticks): """ graph bgp the main graphing function used to graph the given dataset we will be graphing this two ways - full and downsampled for computers that cannot handle the full graph, please use the downsampled data set in order to see the graph without hassle """ # define output html file output_file("bgpgraph.html") # define the figure initial parameters p = figure( title="INTERNET'S REDUNDANCY", # title toolbar_location="above", # toolbar location sizing_mode='stretch_both', # sizing parameters of the graph output_backend="webgl", # allows us to utilize webgl to reduce load ) # draw circles with size 1, color navy, and semi transparent for each datapoint p.circle(x_ticks, redundancy_counts, size=1, color="navy", alpha=0.5) # x axis label p.xaxis.axis_label = 'IPv4 Routes' # y axis label p.yaxis.axis_label = 'AVAILABLE REDUNDANT PATHS' # this allows us to replace our x_ticks with real labels - ip routes p.xaxis.formatter = FuncTickFormatter(code=""" var labels = %s; return labels[tick]; """ % label_dict) # displays graph on default browser show(p)
def plot_bokeh(df,sublist,filename): lenlist=[0] df_sub = df[df['cuisine']==sublist[0]] lenlist.append(df_sub.shape[0]) for cuisine in sublist[1:]: temp = df[df['cuisine']==cuisine] df_sub = pd.concat([df_sub, temp],axis=0,ignore_index=True) lenlist.append(df_sub.shape[0]) df_X = df_sub.drop(['cuisine','recipeName'],axis=1) print df_X.shape, lenlist dist = squareform(pdist(df_X, metric='cosine')) tsne = TSNE(metric='precomputed').fit_transform(dist) #cannot use seaborn palette for bokeh palette =['red','green','blue','yellow'] colors =[] for i in range(len(sublist)): for j in range(lenlist[i+1]-lenlist[i]): colors.append(palette[i]) #plot with boken output_file(filename) source = ColumnDataSource( data=dict(x=tsne[:,0],y=tsne[:,1], cuisine = df_sub['cuisine'], recipe = df_sub['recipeName'])) hover = HoverTool(tooltips=[ ("cuisine", "@cuisine"), ("recipe", "@recipe")]) p = figure(plot_width=1000, plot_height=1000, tools=[hover], title="flavor clustering") p.circle('x', 'y', size=10, source=source,fill_color=colors) show(p)
def create_bar_chart(data, title, x_name, y_name, hover_tool=None, width=1200, height=300): """Creates a bar chart plot with the exact styling for the centcom dashboard. Pass in data as a dictionary, desired plot title, name of x axis, y axis and the hover tool HTML. """ source = ColumnDataSource(data) xdr = FactorRange(factors=data[x_name]) ydr = Range1d(start=0,end=max(data[y_name])*1.5) tools = [] if hover_tool: tools = [hover_tool,] plot = figure(title=title, x_range=xdr, y_range=ydr, plot_width=width, plot_height=height, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location="above", tools=tools, responsive=True, outline_line_color="#666666") glyph = VBar(x=x_name, top=y_name, bottom=0, width=.8, fill_color="#e12127") plot.add_glyph(source, glyph) xaxis = LinearAxis() yaxis = LinearAxis() plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) plot.toolbar.logo = None plot.min_border_top = 0 plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = "#999999" plot.yaxis.axis_label = "Bugs found" plot.ygrid.grid_line_alpha = 0.1 plot.xaxis.axis_label = "Days after app deployment" plot.xaxis.major_label_orientation = 1 return plot
def create_bar_chart(data, title, x_name, y_name, hover_tool=None, width=1200, height=300): """Creates a bar chart plot with the exact styling for the centcom dashboard. Pass in data as a dictionary, desired plot title, name of x axis, y axis and the hover tool HTML. """ source = ColumnDataSource(data) xdr = FactorRange(factors=data[x_name]) ydr = Range1d(start=0,end=max(data[y_name])*1.5) tools = [] if hover_tool: tools = [hover_tool,] plot = figure(title=title, x_range=xdr, y_range=ydr, plot_width=width, plot_height=height, h_symmetry=False, v_symmetry=False, min_border=10, toolbar_location="above", tools=tools, responsive=True, outline_line_color="#666666") glyph = VBar(x=x_name, top=y_name, bottom=0, width=.8, fill_color="#6599ed") plot.add_glyph(source, glyph) xaxis = LinearAxis() yaxis = LinearAxis() plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) plot.toolbar.logo = None plot.min_border_top = 0 plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = "#999999" plot.yaxis.axis_label = "Bugs found" plot.ygrid.grid_line_alpha = 0.1 plot.xaxis.axis_label = "Days after app deployment" plot.xaxis.major_label_orientation = 1 return plot
def test_dash(): a = pd.DataFrame(np.random.randn(10, 10)); b = pd.DataFrame(np.random.randn(10, 10)); plt.figure() plt.plot([1, 2, 3, 4], 'ks-', mec='w', mew=5, ms=20) return Dashboard([a, plt.gcf(), b])
def dashboard_b(): x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y') plot.line(x, y, legend="Temp", line_width=2) a = pd.DataFrame(np.random.randn(20, 20)) b = pd.DataFrame(np.random.randn(10, 10)) c = pd.DataFrame(np.random.randn(5, 5)) d = pd.DataFrame(np.random.randn(1, 1)) return Dashboard([a, b, plot, c, d])
def dashboard_d(): x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y') plot.line(x, y, legend="Temp", line_width=2) a = pd.DataFrame(np.random.randn(20, 20)) b = pd.DataFrame(np.random.randn(10, 10)) c = pd.DataFrame(np.random.randn(5, 5)) d = pd.DataFrame(np.random.randn(50, 50)) return Dashboard([plot, b, c, d], row_layout(2, 2))
def matplot_fig(): plt.figure() plt.plot([1, 2, 3, 4], 'ks-', mec='w', mew=5, ms=20) return plt.gcf()
def matplot_b(): plt.figure() plt.plot([5, 6, 7, 7], 'ks-', mec='w', mew=5, ms=20) return plt.gcf()
def figure_a(): plt.figure() plt.plot([3,1,4,1,20], 'ks-', mec='w', mew=5, ms=20) return plt.gcf()
def figure_e(): x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y') plot.line(x, y, legend="Temp", line_width=2) return plot
def matplot_fig(): plt.figure() plt.plot([3,1,4,1,20], 'ks-', mec='w', mew=5, ms=20) return plt.gcf()
def bokeh_fig(): x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y') plot.line(x, y, legend="Temp", line_width=2) return plot
def bokeh_fig(a, b): x = [1, 2, 3, 4, a] y = [6, 7, 2, 4, b] plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y') plot.line(x, y, legend="Temp", line_width=2) return plot
def figure_e(): x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y', sizing_mode='scale_width') plot.line(x, y, legend="Temp", line_width=2) return plot
def test_matplot(self): plt.figure() plt.plot([3,1,4,1,20], 'ks-', mec='w', mew=5, ms=20) convert_to_html(plt.gcf())
def test_bokeh(self): x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y') plot.line(x, y, legend="Temp", line_width=2) convert_to_html(plot)
def update(self, model): pos_c, neg_c = get_label_colors(PALETTE) color_code = lambda arr: np.where(arr == 1, pos_c, neg_c) self.train_fig = figure(plot_height=400, plot_width=400, title=template_title('train', model.trainerr), tools='', x_range=[0, 100], y_range=[-50, 50]) self.test_fig = figure(plot_height=400, plot_width=400, title=template_title('test', model.testerr), tools='', x_range=[0, 100], y_range=[-50, 50]) if model.surface is not None: X1, X2, Z = model.surface cm = RGBAColorMapper(Z.min(), Z.max(), standard_palettes[PALETTE]) Y = cm.color(Z, alpha=IMAGE_ALPHA) self.train_fig.image_rgba(image=[Y], x=[0], y=[-50], dw=[100], dh=[100]) self.test_fig.image_rgba(image=[Y], x=[0], y=[-50], dw=[100], dh=[100]) sample_weight = model.sample_weight if sample_weight is None: sample_weight = np.ones(model.train.shape[0]) sample_weight = np.sqrt(sample_weight) * DEFAULT_SIZE self.train_fig.circle(x=model.train[:, 0], y=model.train[:, 1], color=color_code(model.train[:, 2]), line_color="#7c7e71", size=sample_weight, fill_alpha=FILL_ALPHA, line_alpha=LINE_ALPHA) self.test_fig.circle(x=model.test[:, 0], y=model.test[:, 1], color=color_code(model.test[:, 2]), line_color="#7c7e71", size=DEFAULT_SIZE, fill_alpha=FILL_ALPHA, line_alpha=LINE_ALPHA) # yeah.. i dont like that either self.layout.children[1].children[1].children[0] = row(self.train_fig, self.test_fig)
def __init__(self, simul, probes, line_kwargs={}, fig_kwargs={}, default_fig_kwargs={"width": 600, "height": 400}, default_line_kwargs={}, notebook=True): from bokeh.io import push_notebook, output_notebook from bokeh.plotting import figure, show, ColumnDataSource from bokeh.layouts import Column if notebook: output_notebook() setattr(self, '_push', push_notebook) self._datasource = ColumnDataSource(dict(t=[simul.t], **{name: [probe(simul.t, simul.fields)] for name, probe in probes.items()})) figs = {} for name, probe in probes.items(): fig_config = default_fig_kwargs.copy() fig_config.update(fig_kwargs.get(name, {})) line_config = default_line_kwargs.copy() line_config.update(line_kwargs.get(name, {})) figs[name] = figure(**fig_config, title=name) figs[name].line('t', name, source=self._datasource, **line_config) self._handler = show(Column(*[figs[name] for name in probes]), notebook_handle=True) self._probes = probes
def image(self, *kargs, **kwargs): fig = figure() fig.image(*kargs, **kwargs) self.figures.append(fig)
def _create_figure(histogram, **kwargs): title = histogram.title or "Histogram" axis_names = histogram.axis_names or ["x", "y"] if len(axis_names) == 1: axis_names = list(axis_names) + ["frequency"] from bokeh.plotting import figure return figure(tools="hover,save,pan,box_zoom,reset,wheel_zoom", toolbar_location='above', x_axis_label=axis_names[0], y_axis_label=axis_names[1], title=title) # All palette names that can be used in cmap argument
def _draw_contigNrPlot(self, scaffolder): plot = figure(title='Number of contigs') plot.circle(x='reads', y='contigs', source=self.contig_read_src, size=10) plot.line(x='reads', y='contigs', line_width=4, source=self.contig_read_src) plot.xaxis.axis_label = '# Reads' plot.yaxis.axis_label = 'Contigs' plot.yaxis.axis_label_text_font_size = '14pt' plot.xaxis.axis_label_text_font_size = '14pt' plot.yaxis.major_label_text_font_size = '14pt' plot.xaxis.major_label_text_font_size = '14pt' plot.title.text_font_size = '16pt' return plot
def _draw_n50Plot(self): plot = figure(title='N50 Values') plot.circle(x='reads', y='n50', source=self.contig_read_src, size=10, color='red') plot.line(x='reads', y='n50', line_width=4, source=self.contig_read_src, color='red') plot.xaxis.axis_label = '# Reads' plot.yaxis.axis_label = 'N50' plot.yaxis.axis_label_text_font_size = '14pt' plot.xaxis.axis_label_text_font_size = '14pt' plot.yaxis.major_label_text_font_size = '14pt' plot.xaxis.major_label_text_font_size = '14pt' plot.yaxis[0].formatter = NumeralTickFormatter(format='0.00a') plot.title.text_font_size = '16pt' return plot
def _draw_contigCirclePlot(self): hover = HoverTool(tooltips=[('Length', '@contigs')]) hover.point_policy = "follow_mouse" plot = figure(x_axis_type=None, y_axis_type=None, tools=[hover], title='Contig lengths') plot.annular_wedge(x=0, y=0, inner_radius=0.5, outer_radius=0.7, start_angle='start', end_angle='stop', color='colors', alpha=0.9, source=self.contig_dist_src) plot.yaxis.axis_label_text_font_size = '14pt' plot.xaxis.axis_label_text_font_size = '14pt' plot.yaxis.major_label_text_font_size = '14pt' plot.xaxis.major_label_text_font_size = '14pt' plot.title.text_font_size = '16pt' return plot