我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用bokeh.models.ColumnDataSource()。
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 update(attr, old, new): new_data = get_ts_data() new_columns = new_data.columns.tolist() new_data.columns = [str(r) for r in list(range(0,len(new_columns)))] empty_nr = 8 - len(new_columns) new_legends = [] for j, new_col in enumerate(new_data.columns): new_source = ColumnDataSource(dict(x=new_data[new_col].index, y=new_data[new_col].values)) rend = fig.renderers[4:-1][j] rend.data_source.data=new_source.data new_legends.append((str(new_columns[j]), [rend])) fig.legend[0].update(legends=new_legends) for j in range(empty_nr-1, 8): new_source = ColumnDataSource(dict(x=[], y=[])) rend = fig.renderers[4:-1][j] rend.data_source.data=new_source.data
def update(attrname, old, new): new_selected, new_x_factors, new_y_factors = get_subset(dictionary_selector.value, dictionary_selector.value) bins = np.linspace(new_selected.counts.min(), new_selected.counts.max(), 10) # bin labels must be one more than len(colorpalette) new_selected["color"] = pd.cut(new_selected.counts, bins, labels = list(reversed(palettes.Blues9)), include_lowest=True) new_selected["wikidataID"] = new_selected["x"].map(lambda x: wikidataIDs.get(x)) fig.xaxis.axis_label = dictionary_selector.value fig.yaxis.axis_label = dictionary_selector.value fig.title.text = "Top %d fact co-occurrences selected" % top_n.value src = ColumnDataSource(dict( x=new_selected["x"].astype(object), y=new_selected["y"].astype(object), color=new_selected["color"].astype(object), wikidataID=new_selected["wikidataID"], counts=new_selected["counts"].astype(int), raw=new_selected["raw"].astype(int))) source.data.update(src.data) fig.x_range.update(factors=new_x_factors[:top_n.value]) fig.y_range.update(factors=new_y_factors[:top_n.value])
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 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 location_plot(title, colors): output_file(title+".html") location_source = ColumnDataSource( data={ "x": whisky[" Latitude"], "y": whisky[" Longitude"], "colors": colors, "regions": whisky.Region, "distilleries": whisky.Distillery } ) fig = figure(title = title, x_axis_location = "above", tools="resize, hover, save") fig.plot_width = 400 fig.plot_height = 500 fig.circle("x", "y", 10, 10, size=9, source=location_source, color='colors', line_color = None) fig.xaxis.major_label_orientation = np.pi / 3 hover = fig.select(dict(type = HoverTool)) hover.tooltips = { "Distillery": "@distilleries", "Location": "(@x, @y)" } show(fig)
def location_plot(title, colors): output_file(title + ".html") location_source = ColumnDataSource( data={ "x": whisky[" Latitude"], "y": whisky[" Longitude"], "colors": colors, "regions": whisky.Region, "distilleries": whisky.Distillery } ) fig = figure(title=title, x_axis_location="above", tools="resize, hover, save") fig.plot_width = 400 fig.plot_height = 500 fig.circle("x", "y", 10, 10, size=9, source=location_source, color='colors', line_color=None) fig.xaxis.major_label_orientation = np.pi / 3 hover = fig.select(dict(type=HoverTool)) hover.tooltips = { "Distillery": "@distilleries", "Location": "(@x, @y)" } show(fig)
def __init__(self, names, initial_size, width=900, height=480): # Call this once to raise an error early if necessary: self._colors = colors.colors(len(names)) self._start = time.perf_counter() self._initial_size = initial_size self._sources = collections.OrderedDict([ (name, { 'hist': bm.ColumnDataSource( data={'top': [], 'left': [], 'right': []}), 'pdf': bm.ColumnDataSource( data={'x': [], 'y': []}), 'stddev': bm.ColumnDataSource( data={'base': [], 'lower': [], 'upper': []}), 'median': bm.ColumnDataSource( data={'x': [], 'y': []}) }) for name in names ]) self._width = width self._height = height self._plot = None self._elapsed_rendering_seconds = 0.0 self._describe_widget = ipdisplay.HTML('')
def get_colorbar_source(df, value_var, colormap): vmax = df[value_var].abs().max() vmin = vmax * -1 norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) value = np.linspace(vmin, vmax, num=50) color = [] for v in value: color.append(mpl.colors.rgb2hex(cm.get_cmap(colormap)(norm(v)))) return vmax*2/49.0, ColumnDataSource(data=dict(value=value, color=color))
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) self.title = Paragraph(text=TITLE) self.data_table = DataTable(source=self.source, width=390, height=275, columns=[ TableColumn(field="zipcode", title="Zipcodes", width=100), TableColumn(field="population", title="Population", width=100, formatter=NumberFormatter(format="0,0")), TableColumn(field="city", title="City") ]) return column(self.title, self.data_table)
def _draw_plots(self, scaffolder): '''Setup all plots.''' self.contig_read_src = ColumnDataSource(dict( reads=[scaffolder.nrReads], contigs=[scaffolder.nrContigs], n50=[scaffolder.N50])) # Calculate data for contig circle plot circle = self._calculate_circle(scaffolder) self.contig_dist_src = ColumnDataSource(dict( start=circle[0], stop=circle[1], colors=circle[2], contigs=circle[3])) self.read_src = ColumnDataSource(dict( nrReads=[], nrPassReads=[], nrFailReads=[], readTime=[])) self.read_hist_src = ColumnDataSource(dict( readLength=[], left=[], right=[])) # Draw plots contigNrPlot = self._draw_contigNrPlot(scaffolder) n50Plot = self._draw_n50Plot() contigCirclePlot = self._draw_contigCirclePlot() readPlot = self._draw_readCountPlot() #readHist = self._draw_readLenHistPlot() # Position plots layout = gridplot([[n50Plot, contigNrPlot], [contigCirclePlot, readPlot]]) try: session = push_session(curdoc()) session.show(layout) except IOError: sys.exit("No bokeh server is running on this host")
def make_source(self): self.main_source = ColumnDataSource(data=self.df)
def plot_Trun(self): star = self.star inst_date = self.inst_date data = self.selected_df idx = data.groupby(['T']).apply(lambda x: x['ccf_max'].idxmax()) highest = data.ix[idx].copy() source = ColumnDataSource(data=highest) self.current_source = source p = figure( title="{} - {}".format(star, inst_date), plot_width=800, plot_height=400, tools="pan,wheel_zoom,tap,hover,reset", title_text_font_size="20pt", ) p.circle("T", "ccf_max", size=10, nonselection_alpha=0.6, source=source ) p.xaxis[0].axis_label = 'Temperature (K)' p.yaxis[0].axis_label = 'CCF Peak Value' hover = p.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("Temperature", "@T"), ("vsini", "@vsini"), ("[Fe/H]", "@feh"), ("log(g)", "@logg"), ("Radial Velocity (km/s)", "@vel_max"), ("ccf peak height", "@ccf_max"), ]) return p, highest
def setup_dashboard(self): output_notebook() x = [0, 1, 1, 2, 2, 3, 3, 4] y = 8*[10 ** -7] source = ColumnDataSource(data=dict(x=x, y=y)) plot = figure(plot_width=300, plot_height=150, y_axis_type="log", y_range=[0.0000000001, 1], x_range=[0, 4], x_axis_label='Epoch', y_axis_label='Learning Rate') plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) learn_inputs = 4 * [3] base_code = """ var data = source.data; var f = cb_obj.value x = data['x'] y = data['y'] y[{}] = Math.pow(10.0, -1.0 * (10-f)) y[{}] = Math.pow(10.0, -1.0 * (10-f)) source.trigger('change'); var command = 'dashboard.learn_inputs[{}] = ' + f; var kernel = IPython.notebook.kernel; kernel.execute(command) """ # set up figure fig = figure(name="cost", y_axis_label="Cost", x_range=(0, 4), x_axis_label="Epoch", plot_width=300, plot_height=300) self.fig = fig train_source = ColumnDataSource(data=dict(x=[], y=[])) train_cost = fig.line('x', 'y', source=train_source) self.train_source = train_source val_source = ColumnDataSource(data=dict(x=[], y=[])) val_cost = fig.line('x', 'y', source=val_source, color='red') self.val_source = val_source # set up sliders and callback callbacks = [CustomJS(args=dict(source=source), code=base_code.format(k, k+1, k/2)) for k in [0, 2, 4, 6]] slider = [Slider(start=0.1, end=10, value=3, step=.1, title=None, callback=C, orientation='vertical', width=80, height=50) for C in callbacks] radio_group = RadioGroup(labels=[""], active=0, width=65) def train_model_button(run=True): train_model(slider, fig=fig, handle=fh, train_source=train_source, val_source=val_source) sliders = row(radio_group, slider[0], slider[1], slider[2], slider[3]) settings = column(plot, sliders) layout = gridplot([[settings, fig]], sizing_mode='fixed', merge_tools=True, toolbar_location=None) self.fh = show(layout, notebook_handle=True)
def __init__(self, name, y_axis_label="", x_axis_label="timestamp", update_period_in_ms=500): self.name = name self.x_axis_label = x_axis_label self.y_axis_label = y_axis_label self.update_period = update_period_in_ms self.source = ColumnDataSource(dict({ self.x_axis_label: [], self.y_axis_label: []} ))
def monitor(gpu_property_string, num_gpus=4): """" Parameters ---------- gpu_property_string: temperature or utilization """ data_dict = {'gpu {}'.format(gpu): [] for gpu in range(num_gpus)} data_dict['index'] = [] data = ColumnDataSource(data=data_dict) p = gpu_plot(data, num_gpus=4, plot_width=600, plot_height=400, y_range=(0, 110)) return p, create_running_func(data, _PROPERTY_DICT[gpu_property_string])
def plot(df, num_gpus=1, plot_width=600, plot_height=400, y_range=(0, 110)): """ """ data = ColumnDataSource(data=df) p = figure(plot_width=plot_width, plot_height=plot_height, y_range=y_range, x_axis_type="datetime") for gpu, color in zip(range(num_gpus), Paired[12]): p.line('timestamp', 'gpu {}'.format(gpu), line_width=4, source=data, color=color, legend="GPU {}".format(gpu)) return p
def init_bokeh_table_data(self): table_data = dict(ids=[], names=[], times=[], inlinetimes=[], plot_inline_times=[], plot_extra_times=[]) self.table_data = ColumnDataSource(table_data)
def _column_data_source(nodes, weights, palette): data = dict( xname=[], yname=[], colors=[], alphas=[], weight=weights.flatten()) for i, node1 in enumerate(nodes): for j, node2 in enumerate(nodes): data['xname'].append(node1['label']) data['yname'].append(node2['label']) if (node1['group'] == node2['group']) and (weights[i, j] > 0): # ingroup relationship group_color = palette[node1['group']] alpha = 1.0 elif (node1['label'] == node2['label']): # diagonal group_color = 'lightgrey' alpha = 0.2 elif (weights[i, j] > 0): # outgroup relationship group_color = 'grey' alpha = 0.9 else: # no relationship group_color = 'lightgrey' alpha = 0.1 data['alphas'].append(alpha) data['colors'].append(group_color) return ColumnDataSource(data)
def modify_doc(doc): data_url = "http://www.neracoos.org/erddap/tabledap/B01_sbe37_all.csvp?time,temperature&depth=1&temperature_qc=0&time>=2016-02-15&time<=2017-03-22" df = pd.read_csv(data_url, parse_dates=True, index_col=0) df = df.rename(columns={'temperature (celsius)': 'temperature'}) df.index.name = 'time' 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(json=yaml.load(""" attrs: Figure: background_fill_color: "#DDDDDD" outline_line_color: white toolbar_location: above height: 500 width: 800 Grid: grid_line_dash: [6, 4] grid_line_color: white """))
def update(attrname, old, new): subset = get_subset(dictchooser.value) new_absolute_source = subset[0] \ .ix[:, :top_n.value] \ .groupby(pd.TimeGrouper(freq=timegroupoptionsmapper[timegroup.active])) \ .sum().fillna(0) new_relative_source = subset[1] \ .ix[:, :top_n.value] \ .groupby(pd.TimeGrouper(freq=timegroupoptionsmapper[timegroup.active])) \ .sum().fillna(0) for old, new in zip(abs_arrangement, new_absolute_source.columns.tolist()): old.title.text = new for old, new in zip(rel_arrangement, new_relative_source.columns.tolist()): old.title.text = new new_abs_sources = [ColumnDataSource(dict(date=new_absolute_source.index, y=new_absolute_source[l])) for l in new_absolute_source.columns.tolist()] new_rel_sources = [ColumnDataSource(dict(date=new_relative_source.index, y=new_relative_source[l])) for l in new_relative_source.columns.tolist()] for old, new in zip(abs_sources, new_abs_sources): old.data.update(new.data) for old, new in zip(rel_sources, new_rel_sources): old.data.update(new.data) new_abs_point_sources = [ColumnDataSource(dict(date=[new_absolute_source[l].idxmax()], y=[new_absolute_source[l].max()], text=[str(int(new_absolute_source[l].max()))] ) ) for l in new_absolute_source.columns.tolist()] new_rel_point_sources = [ColumnDataSource(dict(date=[new_relative_source[l].idxmax()], y=[new_relative_source[l].max()], text=[str(int(new_relative_source[l].max()))] ) ) for l in new_relative_source.columns.tolist()] for old, new in zip(abs_point_sources, new_abs_point_sources): old.data.update(new.data) for old, new in zip(rel_point_sources, new_rel_point_sources): old.data.update(new.data) # Create Input controls
def cumulative_quantiles_plot(samples, plot_width=960, plot_height=480, show_samples=True): '''Plots the cumulative quantiles along with a scatter plot of observations.''' plot = bp.figure(plot_width=960, plot_height=480) names = samples.columns.levels[0] _colors = {name: color for name, color in zip(names, colors.colors(len(names)))} def draw(group): name = group.columns[0][0] color = _colors[name] group.columns = group.columns.droplevel(0) group = group.dropna() quantile_source = bm.ColumnDataSource( pd.DataFrame( data={'lower': group['25%'], 'upper': group['75%']}, index=group.index).dropna().reset_index()) extreme_source = bm.ColumnDataSource( pd.DataFrame( data={'lower': group['min'], 'upper': group['max']}, index=group.index).dropna().reset_index()) plot.line(group.index, group['50%'], line_color=color, legend=name) plot.add_layout(bm.Band(base='time', lower='lower', upper='upper', source=quantile_source, fill_color=color, fill_alpha=0.2)) plot.add_layout(bm.Band(base='time', lower='lower', upper='upper', source=extreme_source, fill_color=color, fill_alpha=0.025)) plot.line('time', 'lower', line_color=color, alpha=0.5, source=extreme_source) plot.line('time', 'upper', line_color=color, alpha=0.5, source=extreme_source) cumulative_quantiles(samples).groupby(axis=1, level=0).apply(draw) if show_samples: def scatter(group): name = group.columns[0][0] color = _colors[name] group = isolate(group) t = timings(group).set_index(group.iloc[:, 1]) t.index.name = 'time' t.columns = ['value'] source = bm.ColumnDataSource(t.reset_index()) plot.circle(x='time', y='value', source=source, color=color, size=1, alpha=0.5) samples.groupby(axis=1, level=0).apply(scatter) bi.show(plot)