Here are the examples of the python api bokeh.models.TextInput taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
10 Examples
3
View Source File : feature.py
License : MIT License
Project Creator : phurwicz
License : MIT License
Project Creator : phurwicz
def _setup_search_widgets(self):
"""
???+ note "Create positive/negative text search boxes."
"""
common_kwargs = dict(width_policy="fit", height_policy="fit")
pos_title, neg_title = "Text contains (python regex):", "Text does not contain:"
self.search_pos = TextInput(title=pos_title, **common_kwargs)
self.search_neg = TextInput(title=neg_title, **common_kwargs)
def _search_watch_widgets(self):
3
View Source File : feature.py
License : MIT License
Project Creator : phurwicz
License : MIT License
Project Creator : phurwicz
def _setup_search_widgets(self):
"""
???+ note "Create similarity search widgets."
"""
self.search_sim = TextInput(
title=f"{self.__class__.PRIMARY_FEATURE} similarity search (enter URL)".capitalize(),
width_policy="fit",
height_policy="fit",
)
self.search_threshold = Slider(
start=0.0,
end=1.0,
value=0.9,
# fewer steps allowed because refreshing search result can be expensive
step=0.1,
title="Similarity threshold",
)
def _search_watch_widgets(self):
0
View Source File : plot.py
License : BSD 3-Clause "New" or "Revised" License
Project Creator : canzarlab
License : BSD 3-Clause "New" or "Revised" License
Project Creator : canzarlab
def interactive(
umap_object,
labels=None,
values=None,
hover_data=None,
theme=None,
cmap="Blues",
color_key=None,
color_key_cmap="Spectral",
background="white",
width=800,
height=800,
point_size=None,
subset_points=None,
interactive_text_search=False,
interactive_text_search_columns=None,
interactive_text_search_alpha_contrast=0.95,
):
"""Create an interactive bokeh plot of a UMAP embedding.
While static plots are useful, sometimes a plot that
supports interactive zooming, and hover tooltips for
individual points is much more desireable. This function
provides a simple interface for creating such plots. The
result is a bokeh plot that will be displayed in a notebook.
Note that more complex tooltips etc. will require custom
code -- this is merely meant to provide fast and easy
access to interactive plotting.
Parameters
----------
umap_object: trained UMAP object
A trained UMAP object that has a 2D embedding.
labels: array, shape (n_samples,) (optional, default None)
An array of labels (assumed integer or categorical),
one for each data sample.
This will be used for coloring the points in
the plot according to their label. Note that
this option is mutually exclusive to the ``values``
option.
values: array, shape (n_samples,) (optional, default None)
An array of values (assumed float or continuous),
one for each sample.
This will be used for coloring the points in
the plot according to a colorscale associated
to the total range of values. Note that this
option is mutually exclusive to the ``labels``
option.
hover_data: DataFrame, shape (n_samples, n_tooltip_features)
(optional, default None)
A dataframe of tooltip data. Each column of the dataframe
should be a Series of length ``n_samples`` providing a value
for each data point. Column names will be used for
identifying information within the tooltip.
theme: string (optional, default None)
A color theme to use for plotting. A small set of
predefined themes are provided which have relatively
good aesthetics. Available themes are:
* 'blue'
* 'red'
* 'green'
* 'inferno'
* 'fire'
* 'viridis'
* 'darkblue'
* 'darkred'
* 'darkgreen'
cmap: string (optional, default 'Blues')
The name of a matplotlib colormap to use for coloring
or shading points. If no labels or values are passed
this will be used for shading points according to
density (largely only of relevance for very large
datasets). If values are passed this will be used for
shading according the value. Note that if theme
is passed then this value will be overridden by the
corresponding option of the theme.
color_key: dict or array, shape (n_categories) (optional, default None)
A way to assign colors to categoricals. This can either be
an explicit dict mapping labels to colors (as strings of form
'#RRGGBB'), or an array like object providing one color for
each distinct category being provided in ``labels``. Either
way this mapping will be used to color points according to
the label. Note that if theme
is passed then this value will be overridden by the
corresponding option of the theme.
color_key_cmap: string (optional, default 'Spectral')
The name of a matplotlib colormap to use for categorical coloring.
If an explicit ``color_key`` is not given a color mapping for
categories can be generated from the label list and selecting
a matching list of colors from the given colormap. Note
that if theme
is passed then this value will be overridden by the
corresponding option of the theme.
background: string (optional, default 'white')
The color of the background. Usually this will be either
'white' or 'black', but any color name will work. Ideally
one wants to match this appropriately to the colors being
used for points etc. This is one of the things that themes
handle for you. Note that if theme
is passed then this value will be overridden by the
corresponding option of the theme.
width: int (optional, default 800)
The desired width of the plot in pixels.
height: int (optional, default 800)
The desired height of the plot in pixels
point_size: int (optional, default None)
The size of each point marker
subset_points: array, shape (n_samples,) (optional, default None)
A way to select a subset of points based on an array of boolean
values.
interactive_text_search: bool (optional, default False)
Whether to include a text search widget above the interactive plot
interactive_text_search_columns: list (optional, default None)
Columns of data source to search. Searches labels and hover_data by default.
interactive_text_search_alpha_contrast: float (optional, default 0.95)
Alpha value for points matching text search. Alpha value for points
not matching text search will be 1 - interactive_text_search_alpha_contrast
Returns
-------
"""
if theme is not None:
cmap = _themes[theme]["cmap"]
color_key_cmap = _themes[theme]["color_key_cmap"]
background = _themes[theme]["background"]
if labels is not None and values is not None:
raise ValueError(
"Conflicting options; only one of labels or values should be set"
)
points = umap_object.embedding_
if subset_points is not None:
if len(subset_points) != points.shape[0]:
raise ValueError(
"Size of subset points ({}) does not match number of input points ({})".format(
len(subset_points), points.shape[0]
)
)
points = points[subset_points]
if points.shape[1] != 2:
raise ValueError("Plotting is currently only implemented for 2D embeddings")
if point_size is None:
point_size = 100.0 / np.sqrt(points.shape[0])
data = pd.DataFrame(umap_object.embedding_, columns=("x", "y"))
if labels is not None:
data["label"] = labels
if color_key is None:
unique_labels = np.unique(labels)
num_labels = unique_labels.shape[0]
color_key = _to_hex(
plt.get_cmap(color_key_cmap)(np.linspace(0, 1, num_labels))
)
if isinstance(color_key, dict):
data["color"] = pd.Series(labels).map(color_key)
else:
unique_labels = np.unique(labels)
if len(color_key) < unique_labels.shape[0]:
raise ValueError(
"Color key must have enough colors for the number of labels"
)
new_color_key = {k: color_key[i] for i, k in enumerate(unique_labels)}
data["color"] = pd.Series(labels).map(new_color_key)
colors = "color"
elif values is not None:
data["value"] = values
palette = _to_hex(plt.get_cmap(cmap)(np.linspace(0, 1, 256)))
colors = btr.linear_cmap(
"value", palette, low=np.min(values), high=np.max(values)
)
else:
colors = matplotlib.colors.rgb2hex(plt.get_cmap(cmap)(0.5))
if subset_points is not None:
data = data[subset_points]
if hover_data is not None:
hover_data = hover_data[subset_points]
if points.shape[0] < = width * height // 10:
if hover_data is not None:
tooltip_dict = {}
for col_name in hover_data:
data[col_name] = hover_data[col_name]
tooltip_dict[col_name] = "@" + col_name
tooltips = list(tooltip_dict.items())
else:
tooltips = None
data["alpha"] = 1
# bpl.output_notebook(hide_banner=True) # this doesn't work for non-notebook use
data_source = bpl.ColumnDataSource(data)
plot = bpl.figure(
width=width,
height=height,
tooltips=tooltips,
background_fill_color=background,
)
plot.circle(
x="x",
y="y",
source=data_source,
color=colors,
size=point_size,
alpha="alpha",
)
plot.grid.visible = False
plot.axis.visible = False
if interactive_text_search:
text_input = TextInput(value="", title="Search:")
if interactive_text_search_columns is None:
interactive_text_search_columns = []
if hover_data is not None:
interactive_text_search_columns.extend(hover_data.columns)
if labels is not None:
interactive_text_search_columns.append("label")
if len(interactive_text_search_columns) == 0:
warn(
"interactive_text_search_columns set to True, but no hover_data or labels provided."
"Please provide hover_data or labels to use interactive text search."
)
else:
callback = CustomJS(
args=dict(
source=data_source,
matching_alpha=interactive_text_search_alpha_contrast,
non_matching_alpha=1 - interactive_text_search_alpha_contrast,
search_columns=interactive_text_search_columns,
),
code="""
var data = source.data;
var text_search = cb_obj.value;
var search_columns_dict = {}
for (var col in search_columns){
search_columns_dict[col] = search_columns[col]
}
// Loop over columns and values
// If there is no match for any column for a given row, change the alpha value
var string_match = false;
for (var i = 0; i < data.x.length; i++) {
string_match = false
for (var j in search_columns_dict) {
if (String(data[search_columns_dict[j]][i]).includes(text_search) ) {
string_match = true
}
}
if (string_match){
data['alpha'][i] = matching_alpha
}else{
data['alpha'][i] = non_matching_alpha
}
}
source.change.emit();
""",
)
text_input.js_on_change("value", callback)
plot = column(text_input, plot)
# bpl.show(plot)
else:
if hover_data is not None:
warn(
"Too many points for hover data -- tooltips will not"
"be displayed. Sorry; try subssampling your data."
)
if interactive_text_search:
warn(
"Too many points for text search." "Sorry; try subssampling your data."
)
hv.extension("bokeh")
hv.output(size=300)
hv.opts('RGB [bgcolor="{}", xaxis=None, yaxis=None]'.format(background))
if labels is not None:
point_plot = hv.Points(data, kdims=["x", "y"])
plot = hd.datashade(
point_plot,
aggregator=ds.count_cat("color"),
color_key=color_key,
cmap=plt.get_cmap(cmap),
width=width,
height=height,
)
elif values is not None:
min_val = data.values.min()
val_range = data.values.max() - min_val
data["val_cat"] = pd.Categorical(
(data.values - min_val) // (val_range // 256)
)
point_plot = hv.Points(data, kdims=["x", "y"], vdims=["val_cat"])
plot = hd.datashade(
point_plot,
aggregator=ds.count_cat("val_cat"),
cmap=plt.get_cmap(cmap),
width=width,
height=height,
)
else:
point_plot = hv.Points(data, kdims=["x", "y"])
plot = hd.datashade(
point_plot,
aggregator=ds.count(),
cmap=plt.get_cmap(cmap),
width=width,
height=height,
)
return plot
0
View Source File : trending_delta4.py
License : MIT License
Project Creator : cutright
License : MIT License
Project Creator : cutright
def __create_widgets(self):
ignored_y = ['Patient Name', 'Patient ID', 'Plan Date', 'Radiation Dev', 'Energy', 'file_name', 'date_time_obj']
y_options = [option for option in list(self.data) if option not in ignored_y]
self.select_y = Select(title='Y-variable:', value='Dose Dev', options=y_options)
linacs = list(set(self.data['Radiation Dev']))
linacs.sort()
linacs.insert(0, 'All')
linacs.append('None')
self.select_linac = {grp: Select(title='Linac %s:' % grp, value='All', options=linacs, width=250)
for grp in GROUPS}
self.select_linac[2].value = 'None'
energies = list(set(self.data['Energy']))
energies.sort()
energies.insert(0, 'Any')
self.select_energies = {grp: Select(title='Energy %s:' % grp, value='Any', options=energies, width=250)
for grp in GROUPS}
self.avg_len_input = TextInput(title='Avg. Len:', value='10', width=100)
self.percentile_input = TextInput(title='Percentile:', value='90', width=100)
self.bins_input = TextInput(title='Bins:', value='20', width=100)
self.start_date_picker = DatePicker(title='Start Date:', value=self.x[0])
self.end_date_picker = DatePicker(title='End Date:', value=self.x[-1])
self.gamma_options = ['5.0%/3.0mm', '3.0%/3.0mm', '3.0%/2.0mm', 'Any']
self.checkbox_button_group = CheckboxButtonGroup(labels=self.gamma_options, active=[3])
def __bind_widgets(self):
0
View Source File : candlestick.py
License : Apache License 2.0
Project Creator : FitzHoo
License : Apache License 2.0
Project Creator : FitzHoo
def candlestick_plot():
def obv_indicator(data):
res = talib.OBV(data.close.values, data.volume.values)
return res
def rsi_indicator(data):
res = talib.RSI(data.close.values, timeperiod=14)
return res
def cci_indicator(data):
res = talib.CCI(data.high.values, data.low.values, data.close.values, timeperiod=14)
return res
def technical_indicator(data, indicator):
if indicator == 'CCI':
data['tech'] = cci_indicator(data)
elif indicator == 'RSI':
data['tech'] = rsi_indicator(data)
else:
data['tech'] = obv_indicator(data)
return data
def load_data(obid, start, end, freq='1d'):
print('running....')
data = get_price(obid, start, end, freqency=freq).reset_index()
data['pct_change'] = data['close'].pct_change()
# data.dropna(inplace=True)
data['pct_change'] = data['pct_change'].apply(lambda x: str(round(x * 100, 2)) + '%')
data['index'] = list(np.arange(len(data)))
data['date'] = data['date'].apply(lambda x: x.strftime("%Y%m%d"))
return data
def moving_average(data, selection):
selection_mapping = {k: int(k.split('_')[-1]) for k in selection}
for k, v in selection_mapping.items():
data[k] = data['close'].rolling(window=v).mean()
return data
def update_lines(attr, old, new):
line_0.visible = 0 in average_selection.active
line_1.visible = 1 in average_selection.active
line_2.visible = 2 in average_selection.active
line_3.visible = 3 in average_selection.active
line_4.visible = 4 in average_selection.active
line_5.visible = 5 in average_selection.active
def update_plot(attr, old, new):
indicator = indicator_selection.value
new_data = technical_indicator(data, indicator)
new_source = ColumnDataSource(new_data)
source.data.update(new_source.data)
def update_data():
# global obid, start, end
obid = order_book_id.value
start = start_date.value
end = end_date.value
# 提取数据,均线根据选取与否进行添加
new_data = load_data(obid, start, end)
new_data_1 = moving_average(new_data, average_labels)
new_data_2 = technical_indicator(new_data, indicator_selection.value)
new_source = ColumnDataSource(new_data_2)
new_source_1 = ColumnDataSource(new_data_1)
source.data.update(new_source.data)
source_1.data.update(new_source_1.data)
inc = new_data.close >= new_data.open
dec = new_data.close < new_data.open
inc_source.data = inc_source.from_df(new_data_2.loc[inc])
dec_source.data = dec_source.from_df(new_data_2.loc[dec])
p.title.text = instruments(obid).symbol
p.x_range.end = len(new_data) + 1
p2.xaxis.major_label_overrides = {i: date for i, date in enumerate(new_data['date'])}
today = datetime.now().date()
average_labels = ["MA_5", "MA_10", "MA_20", 'MA_30', 'MA_60', 'MA_120']
average_selection = CheckboxGroup(labels=average_labels, active=[0, 1, 2, 3, 4, 5, 6])
indicator_selection = Select(title='TechnicalIndicator', value='RSI', options=['OBV', 'RSI', 'CCI'])
order_book_id = TextInput(title='StockCode', value='002916.XSHE')
symbol = instruments(order_book_id.value).symbol
start_date = DatePicker(title="StartDate", value='2018-01-01', min_date='2015-01-01', max_date=today)
end_date = DatePicker(title="EndDate", value=today, min_date=start_date.value, max_date=today)
# labels = [average_selection.labels[i] for i in average_selection.active]
data = load_data(order_book_id.value, start_date.value, end_date.value)
# 均线计算
data_1 = moving_average(data, average_labels) # 计算各种长度的均线
# 技术指标计算
data_2 = technical_indicator(data, indicator_selection.value)
source = ColumnDataSource(data_2)
source_1 = ColumnDataSource(data_1)
inc = data.close >= data.open
dec = data.open > data.close
inc_source = ColumnDataSource(data_2.loc[inc])
dec_source = ColumnDataSource(data_2.loc[dec])
TOOLS = 'save, pan, box_zoom, reset, wheel_zoom'
hover = HoverTool(tooltips=[('date', '@date'),
('open', '@open'),
('high', '@high'),
('low', '@low'),
('close', '@close'),
('pct_change', "@pct_change")
]
)
length = len(data)
p = figure(plot_width=1000, plot_height=500, title='{}'.format(symbol), tools=TOOLS, x_range=(0, length + 1))
p.xaxis.visible = False # 隐藏x-axis
p.min_border_bottom = 0
# 均线图
line_0 = p.line(x='index', y='MA_5', source=source_1, color=Spectral6[5])
line_1 = p.line(x='index', y='MA_10', source=source_1, color=Spectral6[4])
line_2 = p.line(x='index', y='MA_20', source=source_1, color=Spectral6[3])
line_3 = p.line(x='index', y='MA_30', source=source_1, color=Spectral6[2])
line_4 = p.line(x='index', y='MA_60', source=source_1, color=Spectral6[1])
line_5 = p.line(x='index', y='MA_120', source=source_1, color=Spectral6[0])
p.segment(x0='index', y0='high', x1='index', y1='low', color='red', source=inc_source)
p.segment(x0='index', y0='high', x1='index', y1='low', color='green', source=dec_source)
p.vbar('index', 0.5, 'open', 'close', fill_color='red', line_color='red', source=inc_source, hover_fill_alpha=0.5)
p.vbar('index', 0.5, 'open', 'close', fill_color='green', line_color='green', source=dec_source,
hover_fill_alpha=0.5)
p.add_tools(hover)
p1 = figure(plot_width=p.plot_width, plot_height=200, x_range=p.x_range, toolbar_location=None)
p1.vbar('index', 0.5, 0, 'volume', color='red', source=inc_source)
p1.vbar('index', 0.5, 0, 'volume', color='green', source=dec_source)
p1.xaxis.visible = False
p2 = figure(plot_width=p.plot_width, plot_height=p1.plot_height, x_range=p.x_range, toolbar_location=None)
p2.line(x='index', y='tech', source=source)
p2.xaxis.major_label_overrides = {i: date for i, date in enumerate(data['date'])}
p2.xaxis.major_label_orientation = pi / 4
p2.min_border_bottom = 0
button = Button(label="ClickToChange", button_type="success")
button.on_click(update_data)
average_selection.inline = True
average_selection.width = 500
average_selection.on_change('active', update_lines)
indicator_selection.on_change('value', update_plot)
widgets = column(row(order_book_id, start_date, end_date, button), row(indicator_selection, average_selection))
layouts = column(widgets, p, p1, p2)
# doc.add_root(pp)
# make a layout
tab = Panel(child=layouts, title='StockPrice')
return tab
# tabs = Tabs(tabs=[candlestick_plot()])
# curdoc().add_root(tabs)
0
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getLapDelta():
filters, data_table, source, filter_source, track_select, car_select = laptable.create()
acctelemetry.updateTableData(
source, filter_source, track_select, car_select)
def callback_(attrname, old, new):
callback(mode_select.value)
def callback(mode):
idxs = filter_source.selected.indices
if len(idxs) < 2:
layout.children[-1] = tmp
return
df, reference, track, target = None, None, None, None
for i, idx in enumerate(idxs):
# restrict to selected lap
lap = int(filter_source.data['lap'][idx])
name = filter_source.data['name'][idx]
car_model = filter_source.data['car'][idx]
if len(name) > 3 and name[:3] == 'db:':
import pymongo
try:
client = pymongo.MongoClient(os.environ['DB_HOST'], serverSelectionTimeoutMS=10)
db = client.acc
except pymongo.errors.ServerSelectionTimeoutError as err:
print(err)
continue
name = name.split(':')
ds = acctelemetry.DBDataStore(db, *name[1:], lap, car_model)
else:
f_ = os.path.join(os.environ['TELEMETRY_FOLDER'].strip("'"), name)
head_, chans = ldparser.read_ldfile(f_)
laps = np.array(acctelemetry.laps(f_))
# create DataStore that is used later to get pandas DataFrame
ds = acctelemetry.LDDataStore(
chans, laps, acc=head_.event!='AC_LIVE')
ident = filter_source.data['driver'][idx]
if len(ident) == 0:
ident = filter_source.data['car'][idx]
info = [ds, lap, ident, filter_source.data['time'][idx]]
if i == 0:
reference = info
track = filter_source.data['track'][idx]
else:
target = info
if reference is None or target is None:
layout.children[-1] = tmp
return
# text_input.value = "%s: reference: %s (%i) | target: %s (%i)"%(track, reference, idxs[0], target, idxs[-1])
text_input.value = "%s | %s: reference: %s / %s (%i) | target: %s / %s (%i)" % \
(track, mode, reference[2], reference[3], idxs[0],
target[2], target[3], idxs[-1])
layout.children[-1] = getTrackMap(target[:2], reference[:2], mode)
def mode_change(attrname, old, new):
callback(new)
text_input = TextInput(value="nothing selected")
text_input.disabled = True
mode_select = Select(title="Mode:", value='absolut',
options=['absolut',
'gainloss',
'oversteer',
'speed',
'pedals',
'throttle',
'brake',
'g_lon'])
mode_select.on_change('value', mode_change)
filter_source.selected.on_change('indices', callback_)
tmp = figure(plot_height=500, plot_width=800)
layout = column(filters, data_table, mode_select, text_input, tmp, id='lapsdelta', sizing_mode='scale_width')
return layout
color_mode_map = {'absolut': acctelemetry.adddeltacolors,
0
View Source File : config.py
License : GNU General Public License v3.0
Project Creator : happydasch
License : GNU General Public License v3.0
Project Creator : happydasch
def _create_plotgroup_config(self):
self.plotgroup = []
self.plotgroup_chk = defaultdict(list)
self.plotgroup_objs = defaultdict(list)
self.plotgroup_text = None
def active_obj(obj, selected):
if not len(selected) or obj.plotinfo.plotid in selected:
return True
return False
title = Paragraph(
text='Plot Group',
css_classes=['config-title'])
options = []
# get client plot group selection
if self._client.plotgroup != '':
selected_plot_objs = self._client.plotgroup.split(',')
else:
selected_plot_objs = []
# get all plot objects
self.plotgroup_objs = get_plotobjs(
self._figurepage.strategy,
order_by_plotmaster=False)
# create plotgroup checkbox buttons
for d in self.plotgroup_objs:
# generate master chk
master_chk = None
if not isinstance(d, bt.Strategy):
active = []
if active_obj(d, selected_plot_objs):
active.append(0)
self._add_to_plotgroup(d)
master_chk = CheckboxButtonGroup(
labels=[obj2label(d)], active=active)
# generate childs chk
childs_chk = []
objsd = self.plotgroup_objs[d]
# sort child objs by type
objsd.sort(key=lambda x: (FigureType.get_type(x).value))
# split objs into chunks and store chk
objsd = [objsd[i:i + 3] for i in range(0, len(objsd), 3)]
for x in objsd:
childs = []
active = []
for i, o in enumerate(x):
childs.append(obj2label(o))
if active_obj(o, selected_plot_objs):
active.append(i)
self._add_to_plotgroup(o)
# create a chk for every chunk
if len(childs):
chk = CheckboxButtonGroup(
labels=childs, active=active)
chk.on_change(
'active',
partial(
self._on_update_plotgroups,
chk=chk,
master=d,
childs=x))
# if master is not active, disable childs
if master_chk and not len(master_chk.active):
chk.disabled = True
childs_chk.append(chk)
self.plotgroup_chk[d].append(x)
# append title for master (this will also include strategy)
if len(self.plotgroup_objs[d]):
options.append(Paragraph(text=f'{obj2label(d)}:'))
# append master_chk and childs_chk to layout
if master_chk:
master_chk.on_change(
'active',
partial(
self._on_update_plotgroups,
# provide all related chk to master
chk=[master_chk] + childs_chk,
master=d))
options.append(master_chk)
for c in childs_chk:
options.append(c)
# text input to display selection
self.plotgroup_text = TextInput(
value=','.join(self.plotgroup),
disabled=True)
options.append(Paragraph(text='Plot Group Selection:'))
options.append(self.plotgroup_text)
return column([title] + options)
def _add_to_plotgroup(self, obj):
0
View Source File : bokeh_crossplot.py
License : Apache License 2.0
Project Creator : OpendTect
License : Apache License 2.0
Project Creator : OpendTect
def _initui(self):
width = 300
lognms = self.well.getLogNames()
xlognms = ['None'] + lognms
self.logrange = LogRangeWidget(self.well, width=width)
cmap = ColorMapWidget()
self.fields = {
'wellnm': bm.TextInput(title='Well', value=wellnm ),
'xlog': bm.Select(title='X-Axis Log', value=lognms[1], options=lognms),
'ylog': bm.Select(title='Y-Axis Log', value=lognms[2], options=lognms),
'colorlog': bm.Select(title='Color Log', value=xlognms[0], options=xlognms),
'sizelog': bm.Select(title='Size Log', value=xlognms[0], options=xlognms),
'sizemap': bm.RangeSlider(start=0, end=40, value=(6, 25), step=1, title='Size Map'),
'markers': bm.CheckboxGroup(labels=['Show markers'], inline=True, active=[]),
'regression': bm.CheckboxGroup(labels=['Show regression fit'], inline=True, active=[]),
'selected': bm.CheckboxGroup(labels=['For selected only'], inline=True, active=[])
}
self.fields.update(cmap.fields)
self.fields.update(self.logrange.fields)
self.fields['wellnm'].disabled = True
self.layout = bl.column(self.fields['wellnm'],
self.fields['xlog'],
self.fields['ylog'],
self.fields['colorlog'],
self.fields['colormap'],
self.fields['sizelog'],
self.fields['sizemap'],
self.fields['markers'],
self.logrange.layout,
self.fields['regression'],
self.fields['selected'],
width=width,
width_policy='fixed'
)
class CrossplotLogTracks:
0
View Source File : functionality.py
License : MIT License
Project Creator : phurwicz
License : MIT License
Project Creator : phurwicz
def _setup_widgets(self):
"""
???+ note "Create annotator widgets and assign Python callbacks."
"""
from bokeh.models import TextInput
super()._setup_widgets()
self.annotator_input = TextInput(title="Label:")
self.annotator_apply = Button(
label="Apply",
button_type="primary",
height_policy="fit",
width_policy="min",
)
def callback_apply():
"""
A callback on clicking the 'self.annotator_apply' button.
Update labels in the source.
"""
label = self.annotator_input.value
selected_idx = self.sources["raw"].selected.indices
if not selected_idx:
self._warn(
"attempting annotation: did not select any data points. Eligible subset is 'raw'."
)
return
self._info(f"applying {len(selected_idx)} annotations...")
# update label in both the df and the data source
self.dfs["raw"].loc[selected_idx, "label"] = label
patch_to_apply = [(_idx, label) for _idx in selected_idx]
self.sources["raw"].patch({"label": patch_to_apply})
self._good(f"applied {len(selected_idx)} annotations: {label}")
self._update_colors()
# assign the callback and keep the reference
self._callback_apply = callback_apply
self.annotator_apply.on_click(self._callback_apply)
self.annotator_apply.on_click(self._callback_subset_display)
def plot(self):
0
View Source File : experimental.py
License : MIT License
Project Creator : uberdeveloper
License : MIT License
Project Creator : uberdeveloper
def summary_plot(data):
"""
Given a dataframe, create a widget with condition and list
of columns to provide summary data
data
dataframe
Note
-----
* Condition is a valid eval string supported by pandas
* Multiple columns can be selected
* Summary statistics provided by the describe method
"""
from bokeh.models import (
TextInput,
Button,
Select,
MultiSelect,
ColumnDataSource,
PreText,
Paragraph,
)
from bokeh.plotting import figure
from bokeh.layouts import row, column, layout
df = data.copy()
def document(doc):
condition = TextInput(title="Enter your condition")
col = MultiSelect(title="Select the columns", options=list(df.columns))
button = Button(label="Update")
pre = PreText()
pre.text = condition.value
def update():
cond = condition.value
cols = col.value
text = df.query(cond)[cols].describe()
pre.text = str(text)
button.on_click(update)
l = layout([[[condition, button], col], pre])
doc.add_root(l)
return document
def slider_plot(data, cols):