Here are the examples of the python api bokeh.models.Select taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
14 Examples
3
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 getTrackMapPanel(df):
mode_select = Select(title="Mode:", value='speed',
options=['oversteer',
'speed',
'pedals',
'throttle',
'brake',
'g_lon'])
layout = column(mode_select, getTrackMap(df, view='trackmap'))
def mode_change(attrname, old, new):
layout.children[1] = getTrackMap(df, view='trackmap', mode=new)
mode_select.on_change('value', mode_change)
return layout
3
View Source File : bokeh_crossplot.py
License : Apache License 2.0
Project Creator : OpendTect
License : Apache License 2.0
Project Creator : OpendTect
def __init__(self, title='Color Map' ):
self.cmaps = []
for (key,val) in bpal.all_palettes.items():
if 256 in list(val.keys()):
self.cmaps += [key]
self.cmaps.sort()
self.fields = {'colormap': bm.Select(title=title, value='Viridis', options=self.cmaps)}
self.layout = self.fields['colormap']
class CrossplotControls:
3
View Source File : uibokeh_well.py
License : Apache License 2.0
Project Creator : OpendTect
License : Apache License 2.0
Project Creator : OpendTect
def _init_log_ui(self):
lognames = self.well.getLogNames()
line_props = LinePropertyWidget()
self.log_fields= {'log': bm.Select(title='Log Display Styling:', options=lognames),
'left': bm.Spinner(title='Left Limit:'),
'right': bm.Spinner(title='Right Limit:'),
}
self.log_fields.update(line_props.fields)
self.log_fields['log'].on_change('value', self._update_log_selection)
self.log_select.js_link('value',self.log_fields['log'], 'options')
return bl.layout(self.log_fields['log'],
self.log_fields['left'],
self.log_fields['right'],
line_props.layout,
align=('center','start')
)
def _initui(self):
3
View Source File : visualization.py
License : MIT License
Project Creator : pedromartins4
License : MIT License
Project Creator : pedromartins4
def widget_symbols():
# Get all symbols
all_stocks_call = 'https://api.iextrading.com/1.0/ref-data/symbols'
response = requests.get(all_stocks_call)
respon = response.json()
symbols = []
for e in respon:
if e['type'] != 'N/A':
symbols.append(e['symbol'])
select_ticket = Select(value="AAPL", options=symbols)
return select_ticket
def widget_show_text(text):
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 : client.py
License : GNU General Public License v3.0
Project Creator : happydasch
License : GNU General Public License v3.0
Project Creator : happydasch
def _createmodel(self):
def on_select_filter(self, a, old, new):
_logger.debug(f'Switching filter to {new}...')
# ensure datahandler is stopped
self._datahandler.stop()
self._filter = new
self.updatemodel()
_logger.debug('Switching filter finished')
def on_click_nav_action(self):
if not self._paused:
self._pause()
else:
self._resume()
refresh(self)
def on_click_nav_prev(self, steps=1):
self._pause()
self._set_data_by_idx(self._datahandler.get_last_idx() - steps)
update_nav_buttons(self)
def on_click_nav_next(self, steps=1):
self._pause()
self._set_data_by_idx(self._datahandler.get_last_idx() + steps)
update_nav_buttons(self)
def refresh(self):
self.doc.add_next_tick_callback(partial(update_nav_buttons, self))
def reset_nav_buttons(self):
btn_nav_prev.disabled = True
btn_nav_next.disabled = True
btn_nav_action.label = '❙❙'
def update_nav_buttons(self):
last_idx = self._datahandler.get_last_idx()
last_avail_idx = self._app.get_last_idx(self._figid)
if last_idx < self.lookback:
btn_nav_prev.disabled = True
btn_nav_prev_big.disabled = True
else:
btn_nav_prev.disabled = False
btn_nav_prev_big.disabled = False
if last_idx >= last_avail_idx:
btn_nav_next.disabled = True
btn_nav_next_big.disabled = True
else:
btn_nav_next.disabled = False
btn_nav_next_big.disabled = False
if self._paused:
btn_nav_action.label = '▶'
else:
btn_nav_action.label = '❙❙'
# filter selection
datanames = get_datanames(self._strategy)
options = [('', 'Strategy')]
for d in datanames:
options.append(('D' + d, f'Data: {d}'))
options.append(('G', 'Plot Group'))
self._filter = 'D' + datanames[0]
select_filter = Select(
value=self._filter,
options=options)
select_filter.on_change(
'value',
partial(on_select_filter, self))
# nav
btn_nav_prev = Button(label='❮', width=self.NAV_BUTTON_WIDTH)
btn_nav_prev.on_click(partial(on_click_nav_prev, self))
btn_nav_prev_big = Button(label='❮❮', width=self.NAV_BUTTON_WIDTH)
btn_nav_prev_big.on_click(partial(on_click_nav_prev, self, 10))
btn_nav_action = Button(label='❙❙', width=self.NAV_BUTTON_WIDTH)
btn_nav_action.on_click(partial(on_click_nav_action, self))
btn_nav_next = Button(label='❯', width=self.NAV_BUTTON_WIDTH)
btn_nav_next.on_click(partial(on_click_nav_next, self))
btn_nav_next_big = Button(label='❯❯', width=self.NAV_BUTTON_WIDTH)
btn_nav_next_big.on_click(partial(on_click_nav_next, self, 10))
# layout
controls = row(
children=[select_filter])
nav = row(
children=[btn_nav_prev_big,
btn_nav_prev,
btn_nav_action,
btn_nav_next,
btn_nav_next_big])
# tabs
tabs = Tabs(
id='tabs',
sizing_mode=self._app.scheme.plot_sizing_mode)
# model
model = layout(
[
# app settings, top area
[column(controls, width_policy='min'),
Spacer(),
column(nav, width_policy='min')],
Spacer(height=15),
# layout for tabs
[tabs]
],
sizing_mode='stretch_width')
return model, partial(refresh, self)
def updatemodel(self):
0
View Source File : compare_tab.py
License : Apache License 2.0
Project Creator : nancyyanyu
License : Apache License 2.0
Project Creator : nancyyanyu
def compare_plot():
stats = PreText(text='', width=500)
corr = PreText(text='', width=500)
def _ma(series,n):
return series.rolling(window=n).mean()
# connect to Cassandra database
def make_dataset(start='2014-01-01'):
df=pd.DataFrame()
for comp in symbol_list:
database=CassandraStorage(comp)
database.session.row_factory = pandas_factory
database.session.default_fetch_size = None
query="SELECT * FROM {} WHERE time>'{}' ALLOW FILTERING;".format(database.symbol+'_historical',start)
rslt = database.session.execute(query, timeout=None)
df_comp = rslt._current_rows
df_comp['ma5']=_ma(df_comp.adjusted_close,5)
df_comp['ma10']=_ma(df_comp.adjusted_close,10)
df_comp['ma30']=_ma(df_comp.adjusted_close,30)
df=df.append(df_comp)
return df
df_all=make_dataset(start='2014-01-01')
df_init=df_all[df_all.symbol==symbol_list[0]]
source=ColumnDataSource(data= df_init.to_dict('list'))
# hover setting
TOOLTIPS = [
("time", "@time{%F}"),
("adjusted close", "[email protected]_close"),
("close", "[email protected]"),
("open", "[email protected]"),
("high", "[email protected]"),
("low", "[email protected]"),
("volume","@volume")]
formatters={
'time' : 'datetime'}
hover = HoverTool(tooltips=TOOLTIPS,formatters=formatters,mode='vline')
# create plot
p = figure(title='{} (Click on legend entries to hide the corresponding lines)'.format(symbol_list[0]),
plot_height=300,
tools="crosshair,save,undo,xpan,xwheel_zoom,ybox_zoom,reset",
active_scroll='xwheel_zoom',
x_axis_type="datetime",
y_axis_location="left")
p.add_tools(hover)
palte=all_palettes['Set2'][8]
p.line('time', 'adjusted_close', alpha=1.0, line_width=2, color=palte[3], legend='Adjusted Close',source=source)
p.line('time', 'ma5', line_width=1, color=palte[0], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA5',source=source)
p.line('time', 'ma10', line_width=1, color=palte[1], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA10',source=source)
p.line('time', 'ma30', line_width=1, color=palte[2], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA30',source=source)
p.y_range = Range1d(min(source.data['adjusted_close'])*0.3, max(source.data['adjusted_close'])*1.05)
p.extra_y_ranges = {"volumes": Range1d(start=min(source.data['volume'])/2,
end=max(source.data['volume'])*2)}
p.add_layout(LinearAxis(y_range_name="volumes"), 'right')
p.vbar('time', width=3,top='volume', color=choice(all_palettes['Set2'][8]),alpha=0.5, y_range_name="volumes",source=source)
p.legend.location = "top_left"
p.legend.click_policy="hide"
def callback(attr,old,new):
symbol1, symbol2=compare_select1.value, compare_select2.value
df_init1=df_all[df_all.symbol==symbol1]
df_init2=df_all[df_all.symbol==symbol2]
source.data.update( df_init1.to_dict('list'))
p.title.text =symbol1+' (Click on legend entries to hide the corresponding lines)'
p.y_range.start=min(source.data['adjusted_close'])*0.3
p.y_range.end=max(source.data['adjusted_close'])*1.05
p.extra_y_ranges['volumes'].start=min(source.data['volume'])/2.
p.extra_y_ranges['volumes'].end=max(source.data['volume'])*2.
source2.data.update( df_init2.to_dict('list'))
p2.title.text =symbol2+' (Click on legend entries to hide the corresponding lines)'
p2.y_range.start=min(source2.data['adjusted_close'])*0.3
p2.y_range.end=max(source2.data['adjusted_close'])*1.05
p2.extra_y_ranges['volumes'].start=min(source2.data['volume'])/2.
p2.extra_y_ranges['volumes'].end=max(source2.data['volume'])*2.
update_stat(symbol1,symbol2)
def update_stat(symbol1,symbol2):
des=pd.DataFrame()
des[symbol1]=df_all[df_all.symbol==symbol1]['adjusted_close']
des[symbol2]=df_all[df_all.symbol==symbol2]['adjusted_close']
des[symbol1+'_return']=des[symbol1].pct_change()
des[symbol2+'_return']=des[symbol2].pct_change()
stats.text = "Statistics \n"+str(des.describe())
correlation=des[[symbol1+'_return',symbol2+'_return']].corr()
corr.text="Correlation \n"+str(correlation)
update_stat(symbol_list[0],symbol_list[1])
compare_select1=Select(value=symbol_list[0],options=symbol_list)
compare_select1.on_change('value', callback)
"""
Tab2-plot2:
"""
df_init2=df_all[df_all.symbol==symbol_list[1]]
source2=ColumnDataSource(data= df_init2.to_dict('list'))
# create plot
# hover setting
p2 = figure(title='{} (Click on legend entries to hide the corresponding lines)'.format(symbol_list[1]),plot_height=300,
tools="crosshair,save,undo,xpan,xwheel_zoom,ybox_zoom,reset",
active_scroll='xwheel_zoom',
x_axis_type="datetime",
y_axis_location="left")
p2.add_tools(hover)
p2.line('time', 'adjusted_close', alpha=1.0, line_width=2, color=palte[4], legend='Adjusted Close',source=source2)
p2.line('time', 'ma5', line_width=1, color=palte[5], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA5',source=source2)
p2.line('time', 'ma10', line_width=1, color=palte[6], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA10',source=source2)
p2.line('time', 'ma30', line_width=1, color=palte[7], alpha=0.8, muted_color='navy', muted_alpha=0.1, legend='MA30',source=source2)
p2.y_range = Range1d(min(source2.data['adjusted_close'])*0.3, max(source2.data['adjusted_close'])*1.05)
p2.extra_y_ranges = {"volumes": Range1d(start=min(source2.data['volume'])/2,
end=max(source2.data['volume'])*2)}
p2.add_layout(LinearAxis(y_range_name="volumes"), 'right')
p2.vbar('time', width=3,top='volume', color=choice(all_palettes['Set2'][8]),alpha=0.5, y_range_name="volumes",source=source2)
p2.legend.location = "top_left"
p2.legend.click_policy="hide"
compare_select2=Select(value=symbol_list[1],options=symbol_list)
compare_select2.on_change('value', callback)
widget=column(compare_select1,compare_select2)
return p,p2,widget,stats,corr
0
View Source File : economy_tab.py
License : Apache License 2.0
Project Creator : nancyyanyu
License : Apache License 2.0
Project Creator : nancyyanyu
def geomap():
list_d=os.listdir(path+'visualization/bea/')
bea_list=[i[:-4] for i in list_d]
with open(path+'visualization/shapefile/statesGeo.json','r') as f:
geoinfo=json.load(f)
name_default='Real personal income'
def read_bea(name):
df=pd.read_csv(os.path.join(path+'visualization/bea/',name+'.csv'))
df=df[(df.GeoName.isin(geoinfo['state_name'])) & (df.TimePeriod==df.TimePeriod.max())]
try:
df.DataValue=df.DataValue.str.replace(',','').astype(float)
except:
df.DataValue=df.DataValue.astype(float)
data=[df.loc[df.GeoName==i,'DataValue'].values[0] for i in geoinfo['state_name']]
geoinfo['data']=data
source=dict(x=geoinfo['state_lon'],
y=geoinfo['state_lat'],
name=geoinfo['state_name'],
rate=geoinfo['data'])
return source
def make_plot(name):
source=ColumnDataSource(data=read_bea(name))
color_mapper = LogColorMapper(palette=Viridis6)
TOOLS = "pan,wheel_zoom,reset,hover,save"
p = figure(plot_height=500,plot_width=700,
title=name, tools=TOOLS,active_scroll='wheel_zoom',
x_axis_location=None, y_axis_location=None,
tooltips=[("Name", "@name"), (name, "@rate"), ("(Long, Lat)", "($x, $y)")])
p.grid.grid_line_color = None
p.hover.point_policy = "follow_mouse"
p.patches('x', 'y', source=source,
fill_color={'field': 'rate', 'transform': color_mapper},
fill_alpha=0.7, line_color="white", line_width=0.5)
return p,source
p,source=make_plot(name_default)
def callback(attr,old,new):
name=bea_select.value
source.data=read_bea(name)
p.title.text=name
p.hover.tooltips=[("Name", "@name"), (name, "@rate"), ("(Long, Lat)", "($x, $y)")]
bea_select=Select(value=name_default,options=bea_list)
bea_select.on_change('value', callback)
return p,bea_select
def economy_plot():
0
View Source File : economy_tab.py
License : Apache License 2.0
Project Creator : nancyyanyu
License : Apache License 2.0
Project Creator : nancyyanyu
def economy_plot():
list_d=os.listdir(path+'visualization/economy/')
indicator_list=[' '.join(i[:-4].split('_')) for i in list_d]
name1='Real_Gross_Domestic_Product.csv'
name2='All_Employees_Total_Nonfarm_Payrolls.csv'
name3='Consumer_Price_Index_for_All_Urban_Consumers.csv'
name4='Effective_Federal_Funds_Rate.csv'
def read_economy(name):
df=pd.read_csv(os.path.join(path+'visualization/economy/',name))
df.columns=['DATE','DATA']
df.DATE=pd.to_datetime(df.DATE).dt.date
return df
def make_plot(name):
df=read_economy(name)
source = ColumnDataSource(data=df)
title=' '.join(name[:-4].split('_'))
hover = HoverTool(tooltips=[("date", "@DATE{%F}"),('data', "@DATA")],formatters={'DATE': 'datetime'},mode='vline')
e=figure(title=title,plot_height=200,
tools="crosshair,save,undo,xpan,xwheel_zoom,xbox_zoom,reset",
active_scroll='xwheel_zoom',
x_axis_type="datetime")
e.add_tools(hover)
e.line('DATE','DATA',color='black', source=source)
return e,source,title
e1,source1,title1=make_plot(name1)
e2,source2,title2=make_plot(name2)
e3,source3,title3=make_plot(name3)
e4,source4,title4=make_plot(name4)
def callback3(attr,old,new):
indicator1,indicator2,indicator3,indicator4=economy_select1.value,economy_select2.value,economy_select3.value,economy_select4.value
name1,name2,name3,name4=(['_'.join(i.split())+'.csv' for i in [indicator1,indicator2,indicator3,indicator4]])
df1,df2,df3,df4=read_economy(name1),read_economy(name2),read_economy(name3),read_economy(name4)
source1.data,source2.data,source3.data,source4.data = df1.to_dict('list'),df2.to_dict('list'),df3.to_dict('list'),df4.to_dict('list')
e1.title.text,e2.title.text,e3.title.text,e4.title.text =indicator1,indicator2,indicator3,indicator4
e1.y_range.start,e2.y_range.start,e3.y_range.start,e4.y_range.start=min(source1.data['DATA'])/1.05,min(source2.data['DATA'])/1.05,min(source3.data['DATA'])/1.05,min(source4.data['DATA'])/1.05
e1.y_range.end,e2.y_range.end,e3.y_range.end,e4.y_range.end=max(source1.data['DATA'])*1.05,max(source2.data['DATA'])*1.05,max(source3.data['DATA'])*1.05,max(source4.data['DATA'])*1.05
economy_select1=Select(value=title1,options=indicator_list,width=300)
economy_select2=Select(value=title2,options=indicator_list,width=300)
economy_select3=Select(value=title3,options=indicator_list,width=300)
economy_select4=Select(value=title4,options=indicator_list,width=300)
economy_select1.on_change('value', callback3)
economy_select2.on_change('value', callback3)
economy_select3.on_change('value', callback3)
economy_select4.on_change('value', callback3)
return e1,e2,e3,e4,economy_select1,economy_select2,economy_select3,economy_select4
0
View Source File : single_tab.py
License : Apache License 2.0
Project Creator : nancyyanyu
License : Apache License 2.0
Project Creator : nancyyanyu
def candlestick():
if '^GSPC' in symbol_list:
symbol_list.remove('^GSPC')
stock_select=Select(value=symbol_list[0],options=symbol_list)
summaryText = Div(text="",width=400)
financialText=Div(text="",width=180)
def update_summary(symbol):
company,buzzsummary,officerString,institution_df=read_company(symbol)
summaryText.text =""" < b> < p style="color:blue;">Overview: < /p> < /b>
< b>Company: < /b> {} < br>
< b>Address: < /b> {} < br>
< b>City: < /b> {} < br>
< b>State: < /b> {} < br>
< b>Website: < /b> < a href="{}">{} < /a> < br>
< b>Industry: < /b> {} < br>
< b>Sector: < /b> {} < br>
< b>Company Officers: < /b> {} < br>
< b>Summary: < /b> {} < br>""".format(company['price']['longName'],
company['summaryProfile']['address1'],
company['summaryProfile']['city'],
company['summaryProfile']['state'],
company['summaryProfile']['website'],
company['summaryProfile']['website'],
company['summaryProfile']['industry'],
company['summaryProfile']['sector'],
officerString,
buzzsummary)
financialText.text=""" < b> < p style="color:blue;">Financial: < /p> < /b>
< b>Recommendation: {} < /b> < br>
< b>Enterprise Value: < /b> {} < br>
< b>Profit Margins: < /b> {} < br>
< b>Beta: < /b> {} < br>
< b>EBITDA: < /b> {} < br>
< b>Total Debt: < /b> {} < br>
< b>Total Revenue: < /b> {} < br>
< b>DebtToEquity: < /b> {} < br>
< b>Revenue Growth: < /b> {} < br>
< b>Current Ratio: < /b> {} < br>
< b>ROE: < /b> {} < br>
< b>ROA: < /b> {} < br>
< b>Gross Profits: < /b> {} < br>
< b>Quick Ratio: < /b> {} < br>
< b>Free Cashflow: < /b> {} < br>
""".format(company['financialData']['recommendationKey'].upper(),
company['defaultKeyStatistics']['enterpriseValue']['fmt'],
company['defaultKeyStatistics']['profitMargins']['fmt'],
company['defaultKeyStatistics']['beta']['fmt'],
company['financialData']['ebitda']['fmt'],
company['financialData']['totalDebt']['fmt'],
company['financialData']['totalRevenue']['fmt'],
company['financialData']['debtToEquity']['fmt'],
company['financialData']['revenueGrowth']['fmt'],
company['financialData']['currentRatio']['fmt'],
company['financialData']['returnOnAssets']['fmt'],
company['financialData']['returnOnEquity']['fmt'],
company['financialData']['grossProfits']['fmt'],
company['financialData']['quickRatio']['fmt'],
company['financialData']['freeCashflow']['fmt'])
update_summary(stock_select.value)
# connect to Cassandra database
database=CassandraStorage(symbol_list[0])
database.session.row_factory = pandas_factory
database.session.default_fetch_size = None
query="SELECT * FROM {} WHERE time>'2015-01-01' ALLOW FILTERING;".format('{}_historical'.format(symbol_list[0]))
rslt = database.session.execute(query, timeout=None)
df = rslt._current_rows
# create color list
color=df.close>df.open
color=color.replace(True,'green')
color=color.replace(False,'red')
# set data source
source = ColumnDataSource(data=dict(close=list(df.close.values),
adjusted_close=list(df.adjusted_close.values),
open=list(df.open.values),
high=list(df.high.values),
low=list(df.low.values),
volume=list(df.volume.values),
time=list(df.time.dt.date.values),
color=list(color.values)))
# hover setting
TOOLTIPS = [
("time", "@time{%F}"),
("adjusted close", "[email protected]_close"),
("close", "[email protected]"),
("open", "[email protected]"),
("high", "[email protected]"),
("low", "[email protected]"),
("volume","@volume")]
formatters={
'time' : 'datetime'}
hover = HoverTool(tooltips=TOOLTIPS,formatters=formatters,mode='vline')
# create figure
p = figure(title='{} Candlestick'.format(stock_select.value),plot_height=400,
tools="crosshair,save,undo,xpan,xwheel_zoom,xbox_zoom,reset",
active_scroll='xwheel_zoom',
x_axis_type="datetime")
p.add_tools(hover)
p.line('time', 'close', alpha=0.2, line_width=1, color='navy', source=source)
p.segment('time', 'high', 'time', 'low', line_width=1,color="black", source=source)
p.segment('time', 'open', 'time', 'close', line_width=3, color='color', source=source)
p.y_range = Range1d(min(source.data['close'])*0.3, max(source.data['close'])*1.05)
p.extra_y_ranges = {"volumes": Range1d(start=min(source.data['volume'])/2,
end=max(source.data['volume'])*2)}
p.add_layout(LinearAxis(y_range_name="volumes"), 'right')
p.vbar('time', width=3,top='volume', color=choice(all_palettes['Set2'][8]),alpha=0.5, y_range_name="volumes",source=source)
p.xaxis.axis_label = 'Time'
# set data source
_,_,_,institution_df=read_company(symbol_list[0])
source_ins = ColumnDataSource(data=dict(organization=list(institution_df.organization.values),
pctHeld=list(institution_df.pctHeld.values),
position=list(institution_df.position.values),
color=Set3[12][:len(institution_df)]))
s1=figure(x_range=source_ins.data['organization'],plot_height=300,plot_width=700,title='Institution Ownership')
s1.vbar(x='organization', top='position', width=0.8, color='color', source=source_ins)
s1.xaxis.major_label_orientation = pi/7
labels = LabelSet(x='organization', y='position', text='pctHeld', level='glyph',
x_offset=-15, y_offset=-10, source=source_ins, render_mode='canvas',text_font_size="8pt")
s1.add_layout(labels)
# callback funtion for Select tool 'stock_select'
def callback(attr,old,new):
symbol=stock_select.value
_,_,_,institution=read_company(symbol)
if symbol=='S&P500':
symbol='^GSPC'
database=CassandraStorage(symbol)
database.session.row_factory = pandas_factory
database.session.default_fetch_size = None
if symbol=='^GSPC':
symbol='GSPC'
query="SELECT * FROM {} WHERE time>'2015-01-01' ALLOW FILTERING;".format(symbol+'_historical')
rslt = database.session.execute(query, timeout=None)
df = rslt._current_rows
color=df.close>df.open
color=color.replace(True,'green')
color=color.replace(False,'red')
# update source data
source.data=dict(close=list(df.close.values),
adjusted_close=list(df.adjusted_close.values),
open=list(df.open.values),
high=list(df.high.values),
low=list(df.low.values),
volume=list(df.volume.values),
time=list(df.time.dt.date.values),
color=list(color.values))
source_ins.data=dict(organization=list(institution.organization.values),
pctHeld=list(institution.pctHeld.values),
position=list(institution.position.values),
color=Set3[12][:len(institution)])
p.title.text=symbol+' Candlestick'
p.y_range.start=min(source.data['close'])*0.3
p.y_range.end=max(source.data['close'])*1.05
p.extra_y_ranges['volumes'].start=min(source.data['volume'])/2.
p.extra_y_ranges['volumes'].end=max(source.data['volume'])*2.
s1.x_range.factors=source_ins.data['organization']
update_summary(symbol)
stock_select.on_change('value', callback)
return p,stock_select,summaryText,financialText,s1
def stream_price():
0
View Source File : geoplot.py
License : MIT License
Project Creator : PatrikHlobil
License : MIT License
Project Creator : PatrikHlobil
def geoplot( # noqa C901
gdf_in,
geometry_column="geometry",
figure=None,
figsize=None,
title="",
xlabel="Longitude",
ylabel="Latitude",
xlim=None,
ylim=None,
color="blue",
colormap=None,
colormap_uselog=False,
colormap_range=None,
category=None,
dropdown=None,
slider=None,
slider_range=None,
slider_name="",
show_colorbar=True,
colorbar_tick_format=None,
xrange=None,
yrange=None,
hovertool=True,
hovertool_columns=[],
hovertool_string=None,
simplify_shapes=None,
tile_provider="CARTODBPOSITRON_RETINA",
tile_provider_url=None,
tile_attribution="",
tile_alpha=1,
panning=True,
zooming=True,
toolbar_location="right",
show_figure=True,
return_figure=True,
return_html=False,
legend=True,
webgl=True,
**kwargs,
):
"""Doc-String: TODO"""
# Imports:
import bokeh.plotting
from bokeh.layouts import column, row
from bokeh.models import (
BasicTicker,
BoxZoomTool,
ColorBar,
ColumnDataSource,
GeoJSONDataSource,
HoverTool,
LinearColorMapper,
LogColorMapper,
LogTicker,
Select,
Slider,
WheelZoomTool,
)
from bokeh.models.callbacks import CustomJS
from bokeh.models.widgets import Dropdown
from bokeh.palettes import all_palettes
from bokeh.plotting import show
# Make a copy of the input geodataframe:
gdf = gdf_in.copy()
# Check layertypes:
if type(gdf) != pd.DataFrame:
layertypes = []
if "Point" in str(gdf.geom_type.unique()):
layertypes.append("Point")
if "Line" in str(gdf.geom_type.unique()):
layertypes.append("Line")
if "Polygon" in str(gdf.geom_type.unique()):
layertypes.append("Polygon")
if len(layertypes) > 1:
raise Exception(
f"Can only plot GeoDataFrames/Series with single type of geometry (either Point, Line or Polygon). Provided is a GeoDataFrame/Series with types: {layertypes}"
)
else:
layertypes = ["Point"]
# Get and check provided parameters for geoplot:
figure_options = {
"title": title,
"x_axis_label": xlabel,
"y_axis_label": ylabel,
"plot_width": 600,
"plot_height": 400,
"toolbar_location": toolbar_location,
"active_scroll": "wheel_zoom",
"x_axis_type": "mercator",
"y_axis_type": "mercator",
"match_aspect": True,
}
if figsize is not None:
width, height = figsize
figure_options["plot_width"] = width
figure_options["plot_height"] = height
if webgl:
figure_options["output_backend"] = "webgl"
if type(gdf) != pd.DataFrame:
# Convert GeoDataFrame to Web Mercator Projection:
gdf.to_crs(epsg=3857, inplace=True)
# Simplify shapes if wanted:
if isinstance(simplify_shapes, numbers.Number):
if layertypes[0] in ["Line", "Polygon"]:
gdf[geometry_column] = gdf[geometry_column].simplify(simplify_shapes)
elif simplify_shapes is not None:
raise ValueError(
" < simplify_shapes> parameter only accepts numbers or None."
)
# Check for category, dropdown or slider (choropleth map column):
category_options = 0
if category is not None:
category_options += 1
category_columns = [category]
if dropdown is not None:
category_options += 1
category_columns = dropdown
if slider is not None:
category_options += 1
category_columns = slider
if category_options > 1:
raise ValueError(
"Only one of < category>, < dropdown> or < slider> parameters is allowed to be used at once."
)
# Check for category (single choropleth plot):
if category is None:
pass
elif isinstance(category, (list, tuple)):
raise ValueError(
"For < category>, please provide an existing single column of the GeoDataFrame."
)
elif category in gdf.columns:
pass
else:
raise ValueError(
f"Could not find column '{category}' in GeoDataFrame. For < category>, please provide an existing single column of the GeoDataFrame."
)
# Check for dropdown (multiple choropleth plots via dropdown selection):
if dropdown is None:
pass
elif not isinstance(dropdown, (list, tuple)):
raise ValueError(
"For < dropdown>, please provide a list/tuple of existing columns of the GeoDataFrame."
)
else:
for col in dropdown:
if col not in gdf.columns:
raise ValueError(
f"Could not find column '{col}' for < dropdown> in GeoDataFrame. "
)
# Check for slider (multiple choropleth plots via slider selection):
if slider is None:
pass
elif not isinstance(slider, (list, tuple)):
raise ValueError(
"For < slider>, please provide a list/tuple of existing columns of the GeoDataFrame."
)
else:
for col in slider:
if col not in gdf.columns:
raise ValueError(
f"Could not find column '{col}' for < slider> in GeoDataFrame. "
)
if slider_range is not None:
if not isinstance(slider_range, Iterable):
raise ValueError(
" < slider_range> has to be a type that is iterable like list, tuple, range, ..."
)
else:
slider_range = list(slider_range)
if len(slider_range) != len(slider):
raise ValueError(
"The number of elements in < slider_range> has to be the same as in < slider>."
)
steps = []
for i in range(len(slider_range) - 1):
steps.append(slider_range[i + 1] - slider_range[i])
if len(set(steps)) > 1:
raise ValueError(
" < slider_range> has to have equal step size between each elements (like a range-object)."
)
else:
slider_step = steps[0]
slider_start = slider_range[0]
slider_end = slider_range[-1]
# Check colormap if either < category>, < dropdown> or < slider> is choosen:
if category_options == 1:
if colormap is None:
colormap = blue_colormap
elif isinstance(colormap, (tuple, list)):
if len(colormap) > 1:
pass
else:
raise ValueError(
f" < colormap> only accepts a list/tuple of at least two colors or the name of one of the following predefined colormaps (see also https://bokeh.pydata.org/en/latest/docs/reference/palettes.html ): {list(all_palettes.keys())}"
)
elif isinstance(colormap, str):
if colormap in all_palettes:
colormap = all_palettes[colormap]
colormap = colormap[max(colormap.keys())]
else:
raise ValueError(
f"Could not find < colormap> with name {colormap}. The following predefined colormaps are supported (see also https://bokeh.pydata.org/en/latest/docs/reference/palettes.html ): {list(all_palettes.keys())}"
)
else:
raise ValueError(
f" < colormap> only accepts a list/tuple of at least two colors or the name of one of the following predefined colormaps (see also https://bokeh.pydata.org/en/latest/docs/reference/palettes.html ): {list(all_palettes.keys())}"
)
else:
if isinstance(color, str):
colormap = [color]
elif color is None:
colormap = ["blue"]
else:
raise ValueError(
" < color> has to be a string specifying the fill_color of the map glyph."
)
# Check xlim & ylim:
if xlim is not None:
if isinstance(xlim, (tuple, list)):
if len(xlim) == 2:
xmin, xmax = xlim
for _ in [xmin, xmax]:
if not -180 < _ < = 180:
raise ValueError(
"Limits for x-axis (=Longitude) have to be between -180 and 180."
)
if not xmin < xmax:
raise ValueError("xmin has to be smaller than xmax.")
from pyproj import Transformer
transformer = Transformer.from_crs("epsg:4326", "epsg:3857")
xmin = transformer.transform(0, xmin)[0]
xmax = transformer.transform(0, xmax)[0]
figure_options["x_range"] = (xmin, xmax)
else:
raise ValueError(
"Limits for x-axis (=Longitude) have to be of form [xmin, xmax] with values between -180 and 180."
)
else:
raise ValueError(
"Limits for x-axis (=Longitude) have to be of form [xmin, xmax] with values between -180 and 180."
)
if ylim is not None:
if isinstance(ylim, (tuple, list)):
if len(ylim) == 2:
ymin, ymax = ylim
for _ in [ymin, ymax]:
if not -90 < _ < = 90:
raise ValueError(
"Limits for y-axis (=Latitude) have to be between -90 and 90."
)
if not ymin < ymax:
raise ValueError("ymin has to be smaller than ymax.")
from pyproj import Transformer
transformer = Transformer.from_crs("epsg:4326", "epsg:3857")
ymin = transformer.transform(ymin, 0)[1]
ymax = transformer.transform(ymax, 0)[1]
figure_options["y_range"] = (ymin, ymax)
else:
raise ValueError(
"Limits for y-axis (=Latitude) have to be of form [ymin, ymax] with values between -90 and 90."
)
else:
raise ValueError(
"Limits for y-axis (=Latitude) have to be of form [ymin, ymax] with values between -90 and 90."
)
# Create Figure to draw:
old_layout = None
if figure is None:
figure_options["x_axis_label"] = (
figure_options["x_axis_label"]
if figure_options["x_axis_label"] is not None
else "Longitute"
)
figure_options["y_axis_label"] = (
figure_options["y_axis_label"]
if figure_options["y_axis_label"] is not None
else "Latitude"
)
p = bokeh.plotting.figure(**figure_options)
# Add Tile Source as Background:
p = _add_backgroundtile(
p, tile_provider, tile_provider_url, tile_attribution, tile_alpha
)
elif isinstance(figure, type(bokeh.plotting.figure())):
p = figure
elif isinstance(figure, type(column())):
old_layout = figure
p = _get_figure(old_layout)
else:
raise ValueError(
"Parameter < figure> has to be of type bokeh.plotting.figure or bokeh.layouts.column."
)
for t in p.tools:
# Get ridd of zoom on axes:
if isinstance(t, WheelZoomTool):
t.zoom_on_axis = False
# Make sure that box zoom matches aspect:
if isinstance(t, BoxZoomTool):
t.match_aspect = True
# Hide legend if wanted:
legend_input = legend
if isinstance(legend, str):
pass
else:
legend = "GeoLayer"
# Define colormapper:
if len(colormap) == 1:
kwargs["fill_color"] = colormap[0]
elif category is not None:
# Check if category column is numerical:
if not issubclass(gdf[category].dtype.type, np.number):
raise NotImplementedError(
f" < category> plot only yet implemented for numerical columns. Column '{category}' is not numerical."
)
field = category
colormapper_options = {"palette": colormap}
if colormap_range is not None:
if not isinstance(colormap_range, (tuple, list)):
raise ValueError(
" < colormap_range> can only be 'None' or a tuple/list of form (min, max)."
)
elif len(colormap_range) == 2:
colormapper_options["low"] = colormap_range[0]
colormapper_options["high"] = colormap_range[1]
else:
colormapper_options["low"] = gdf[field].min()
colormapper_options["high"] = gdf[field].max()
if colormap_uselog:
colormapper = LogColorMapper(**colormapper_options)
else:
colormapper = LinearColorMapper(**colormapper_options)
kwargs["fill_color"] = {"field": "Colormap", "transform": colormapper}
if not isinstance(legend, str):
legend = str(field)
elif dropdown is not None:
# Check if all columns in dropdown selection are numerical:
for col in dropdown:
if not issubclass(gdf[col].dtype.type, np.number):
raise NotImplementedError(
f" < dropdown> plot only yet implemented for numerical columns. Column '{col}' is not numerical."
)
field = dropdown[0]
colormapper_options = {"palette": colormap}
if colormap_range is not None:
if not isinstance(colormap_range, (tuple, list)):
raise ValueError(
" < colormap_range> can only be 'None' or a tuple/list of form (min, max)."
)
elif len(colormap_range) == 2:
colormapper_options["low"] = colormap_range[0]
colormapper_options["high"] = colormap_range[1]
else:
colormapper_options["low"] = gdf[dropdown].min().min()
colormapper_options["high"] = gdf[dropdown].max().max()
if colormap_uselog:
colormapper = LogColorMapper(**colormapper_options)
else:
colormapper = LinearColorMapper(**colormapper_options)
kwargs["fill_color"] = {"field": "Colormap", "transform": colormapper}
legend = " " + field
elif slider is not None:
# Check if all columns in dropdown selection are numerical:
for col in slider:
if not issubclass(gdf[col].dtype.type, np.number):
raise NotImplementedError(
f" < slider> plot only yet implemented for numerical columns. Column '{col}' is not numerical."
)
field = slider[0]
colormapper_options = {"palette": colormap}
if colormap_range is not None:
if not isinstance(colormap_range, (tuple, list)):
raise ValueError(
" < colormap_range> can only be 'None' or a tuple/list of form (min, max)."
)
elif len(colormap_range) == 2:
colormapper_options["low"] = colormap_range[0]
colormapper_options["high"] = colormap_range[1]
else:
colormapper_options["low"] = gdf[slider].min().min()
colormapper_options["high"] = gdf[slider].max().max()
if colormap_uselog:
colormapper = LogColorMapper(**colormapper_options)
else:
colormapper = LinearColorMapper(**colormapper_options)
kwargs["fill_color"] = {"field": "Colormap", "transform": colormapper}
if not isinstance(legend, str):
legend = "Geolayer"
# Check that only hovertool_columns or hovertool_string is used:
if isinstance(hovertool_columns, (list, tuple, str)):
if len(hovertool_columns) > 0 and hovertool_string is not None:
raise ValueError(
"Either < hovertool_columns> or < hovertool_string> can be used, but not both at the same time."
)
else:
raise ValueError(
" < hovertool_columns> has to be a list of columns of the GeoDataFrame or the string 'all'."
)
if hovertool_string is not None:
hovertool_columns = "all"
# Check for Hovertool columns:
if hovertool:
if not isinstance(hovertool_columns, (list, tuple)):
if hovertool_columns == "all":
hovertool_columns = list(
filter(lambda col: col != geometry_column, gdf.columns)
)
else:
raise ValueError(
" < hovertool_columns> has to be a list of columns of the GeoDataFrame or the string 'all'."
)
elif len(hovertool_columns) == 0:
if category is not None:
hovertool_columns = [category]
elif dropdown is not None:
hovertool_columns = dropdown
elif slider is not None:
hovertool_columns = slider
else:
hovertool_columns = []
else:
for col in hovertool_columns:
if col not in gdf.columns:
raise ValueError(
f"Could not find columns '{col}' in GeoDataFrame. < hovertool_columns> has to be a list of columns of the GeoDataFrame or the string 'all'."
)
else:
if category is None:
hovertool_columns = []
else:
hovertool_columns = [category]
# Reduce DataFrame to needed columns:
if type(gdf) == pd.DataFrame:
gdf["Geometry"] = 0
additional_columns = ["x", "y"]
else:
additional_columns = [geometry_column]
for kwarg, value in kwargs.items():
if isinstance(value, Hashable):
if value in gdf.columns:
additional_columns.append(value)
if category_options == 0:
gdf = gdf[list(set(hovertool_columns) | set(additional_columns))]
else:
gdf = gdf[
list(
set(hovertool_columns) | set(category_columns) | set(additional_columns)
)
]
gdf["Colormap"] = gdf[field]
field = "Colormap"
# Create GeoJSON DataSource for Plot:
if type(gdf) != pd.DataFrame:
geo_source = GeoJSONDataSource(geojson=gdf.to_json())
else:
geo_source = gdf
# Draw Glyph on Figure:
layout = None
if "Point" in layertypes:
if "line_color" not in kwargs:
kwargs["line_color"] = kwargs["fill_color"]
glyph = p.scatter(
x="x", y="y", source=geo_source, legend_label=legend, **kwargs
)
if "Line" in layertypes:
if "line_color" not in kwargs:
kwargs["line_color"] = kwargs["fill_color"]
del kwargs["fill_color"]
glyph = p.multi_line(
xs="xs", ys="ys", source=geo_source, legend_label=legend, **kwargs
)
if "Polygon" in layertypes:
if "line_color" not in kwargs:
kwargs["line_color"] = "black"
# Creates from a geoDataFrame with Polygons and Multipolygons a Pandas DataFrame
# with x any y columns specifying the geometry of the Polygons:
geo_source = ColumnDataSource(
convert_geoDataFrame_to_patches(gdf, geometry_column)
)
# Plot polygons:
glyph = p.multi_polygons(
xs="__x__", ys="__y__", source=geo_source, legend_label=legend, **kwargs
)
# Add hovertool:
if hovertool and (category_options == 1 or len(hovertool_columns) > 0):
my_hover = HoverTool(renderers=[glyph])
if hovertool_string is None:
my_hover.tooltips = [(str(col), "@{%s}" % col) for col in hovertool_columns]
else:
my_hover.tooltips = hovertool_string
p.add_tools(my_hover)
# Add colorbar:
if show_colorbar and category_options == 1:
colorbar_options = {
"color_mapper": colormapper,
"label_standoff": 12,
"border_line_color": None,
"location": (0, 0),
}
if colormap_uselog:
colorbar_options["ticker"] = LogTicker()
if colorbar_tick_format:
colorbar_options["formatter"] = get_tick_formatter(colorbar_tick_format)
colorbar = ColorBar(**colorbar_options)
p.add_layout(colorbar, "right")
# Add Dropdown Widget:
if dropdown is not None:
# Define Dropdown widget:
dropdown_widget = Select(
title="Select Choropleth Layer", options=list(zip(dropdown, dropdown))
)
# Define Callback for Dropdown widget:
callback = CustomJS(
args=dict(
dropdown_widget=dropdown_widget,
geo_source=geo_source,
legend=p.legend[0].items[0],
),
code="""
//Change selection of field for Colormapper for choropleth plot:
geo_source.data["Colormap"] = geo_source.data[dropdown_widget.value];
geo_source.change.emit();
//Change label of Legend:
legend.label["value"] = " " + dropdown_widget.value;
""",
)
dropdown_widget.js_on_change("value", callback)
# Add Dropdown widget above the plot:
if old_layout is None:
layout = column(dropdown_widget, p)
else:
layout = column(dropdown_widget, old_layout)
# Add Slider Widget:
if slider is not None:
if slider_range is None:
slider_start = 0
slider_end = len(slider) - 1
slider_step = 1
value2name = ColumnDataSource(
{
"Values": np.arange(
slider_start, slider_end + slider_step, slider_step
),
"Names": slider,
}
)
# Define Slider widget:
slider_widget = Slider(
start=slider_start,
end=slider_end,
value=slider_start,
step=slider_step,
title=slider_name,
)
# Define Callback for Slider widget:
callback = CustomJS(
args=dict(
slider_widget=slider_widget,
geo_source=geo_source,
value2name=value2name,
),
code="""
//Change selection of field for Colormapper for choropleth plot:
var slider_value = slider_widget.value;
var i;
for(i=0; i < value2name.data["Names"].length; i++)
{
if (value2name.data["Values"][i] == slider_value)
{
var name = value2name.data["Names"][i];
}
}
geo_source.data["Colormap"] = geo_source.data[name];
geo_source.change.emit();
""",
)
slider_widget.js_on_change("value", callback)
# Add Slider widget above the plot:
if old_layout is None:
layout = column(slider_widget, p)
else:
layout = column(slider_widget, old_layout)
# Hide legend if user wants:
if legend_input is False:
p.legend.visible = False
# Set click policy for legend:
p.legend.click_policy = "hide"
# Set panning option:
if panning is False:
p.toolbar.active_drag = None
# Set zooming option:
if zooming is False:
p.toolbar.active_scroll = None
# Display plot and if wanted return plot:
if layout is None:
if old_layout is None:
layout = p
else:
layout = old_layout
# Display plot if wanted
if show_figure:
show(layout)
# Return as (embeddable) HTML if wanted:
if return_html:
return embedded_html(layout)
# Return plot:
if return_figure:
return layout
0
View Source File : render.py
License : MIT License
Project Creator : sfu-db
License : MIT License
Project Creator : sfu-db
def render_crossfilter(
itmdt: Intermediate, plot_width: int, plot_height: int, cfg: Config
) -> column:
"""
Render crossfilter scatter plot with a regression line.
"""
# pylint: disable=too-many-locals, too-many-function-args
if cfg.interactions.cat_enable:
all_cols = itmdt["all_cols"]
else:
all_cols = itmdt["num_cols"]
scatter_df = itmdt["scatter_source"]
# all other plots except for scatter plot, used for cat-cat and cat-num interactions.
other_plots = itmdt["other_plots"]
if scatter_df.empty:
scatter_df["__x__"] = [None] * len(itmdt["scatter_source"])
scatter_df["__y__"] = [None] * len(itmdt["scatter_source"])
else:
scatter_df["__x__"] = scatter_df[scatter_df.columns[0]]
scatter_df["__y__"] = scatter_df[scatter_df.columns[0]]
source_scatter = ColumnDataSource(scatter_df)
source_xy_value = ColumnDataSource({"x": [scatter_df.columns[0]], "y": [scatter_df.columns[0]]})
var_list = list(all_cols)
xcol = source_xy_value.data["x"][0]
ycol = source_xy_value.data["y"][0]
tooltips = [("X-Axis: ", "@__x__"), ("Y-Axis: ", "@__y__")]
scatter_fig = Figure(
plot_width=plot_width,
plot_height=plot_height,
toolbar_location=None,
title=Title(text="Scatter Plot", align="center"),
tools=[],
x_axis_label=xcol,
y_axis_label=ycol,
)
scatter = scatter_fig.scatter("__x__", "__y__", source=source_scatter)
hover = HoverTool(tooltips=tooltips, renderers=[scatter])
scatter_fig.add_tools(hover)
fig_all_in_one = column(scatter_fig, sizing_mode="stretch_width")
x_select = Select(title="X-Axis", value=xcol, options=var_list, width=150)
y_select = Select(title="Y-Axis", value=ycol, options=var_list, width=150)
x_select.js_on_change(
"value",
CustomJS(
args=dict(
scatter=source_scatter,
xy_value=source_xy_value,
fig_all_in_one=fig_all_in_one,
scatter_plot=scatter_fig,
x_axis=scatter_fig.xaxis[0],
other_plots=other_plots,
),
code="""
let currentSelect = this.value;
let xyValueData = xy_value.data;
let scatterData = scatter.data;
xyValueData['x'][0] = currentSelect;
xy_value.change.emit();
const children = []
let ycol = xyValueData['y'][0];
let col = currentSelect + '_' + ycol
if (col in other_plots) {
children.push(other_plots[col])
}
else {
scatterData['__x__'] = scatterData[currentSelect];
x_axis.axis_label = currentSelect;
scatter.change.emit();
children.push(scatter_plot)
}
fig_all_in_one.children = children;
""",
),
)
y_select.js_on_change(
"value",
CustomJS(
args=dict(
scatter=source_scatter,
xy_value=source_xy_value,
fig_all_in_one=fig_all_in_one,
scatter_plot=scatter_fig,
y_axis=scatter_fig.yaxis[0],
other_plots=other_plots,
),
code="""
let ycol = this.value;
let xyValueData = xy_value.data;
let scatterData = scatter.data;
xyValueData['y'][0] = ycol;
xy_value.change.emit();
const children = []
let xcol = xyValueData['x'][0];
let col = xcol + '_' + ycol;
if (col in other_plots) {
children.push(other_plots[col])
}
else {
scatterData['__y__'] = scatterData[ycol];
y_axis.axis_label = ycol;
scatter.change.emit();
children.push(scatter_plot)
}
fig_all_in_one.children = children;
""",
),
)
interaction_fig = column(
row(x_select, y_select, align="center"), fig_all_in_one, sizing_mode="stretch_width"
)
return interaction_fig
# ######### Interactions for report #########
# def render_crossfilter(
# itmdt: Intermediate, plot_width: int, plot_height: int
# ) -> column:
# """
# Render crossfilter scatter plot with a regression line.
# """
# # pylint: disable=too-many-locals, too-many-function-args
# source_scatter = ColumnDataSource(itmdt["data"])
# source_coeffs = ColumnDataSource(itmdt["coeffs"])
# source_xy_value = ColumnDataSource(
# {"x": [itmdt["data"].columns[0]], "y": [itmdt["data"].columns[0]]}
# )
# var_list = list(itmdt["data"].columns)[0:-2]
# xcol = source_xy_value.data["x"][0]
# ycol = source_xy_value.data["y"][0]
# tooltips = [("X-Axis: ", "@__x__"), ("Y-Axis: ", "@__y__")]
# fig = Figure(
# plot_width=plot_width,
# plot_height=plot_height,
# toolbar_location=None,
# title=Title(text="Scatter Plot & Regression Line", align="center"),
# tools=[],
# x_axis_label=xcol,
# y_axis_label=ycol,
# )
# scatter = fig.scatter("__x__", "__y__", source=source_scatter)
# fig.line("__x__", "__y__", source=source_coeffs, line_width=3)
# # Not adding the tooltips before because we only want to apply tooltip to the scatter
# hover = HoverTool(tooltips=tooltips, renderers=[scatter])
# fig.add_tools(hover)
# x_select = Select(title="X-Axis", value=xcol, options=var_list, width=150)
# y_select = Select(title="Y-Axis", value=ycol, options=var_list, width=150)
# x_select.js_on_change(
# "value",
# CustomJS(
# args=dict(
# scatter=source_scatter,
# coeffs=source_coeffs,
# xy_value=source_xy_value,
# x_axis=fig.xaxis[0],
# ),
# code="""
# let currentSelect = this.value;
# let xyValueData = xy_value.data;
# let scatterData = scatter.data;
# let coeffsData = coeffs.data;
# xyValueData['x'][0] = currentSelect;
# scatterData['__x__'] = scatterData[currentSelect];
# coeffsData['__x__'] = coeffsData[`${currentSelect}${xyValueData['y'][0]}x`];
# coeffsData['__y__'] = coeffsData[`${currentSelect}${xyValueData['y'][0]}y`];
# x_axis.axis_label = currentSelect;
# scatter.change.emit();
# coeffs.change.emit();
# xy_value.change.emit();
# """,
# ),
# )
# y_select.js_on_change(
# "value",
# CustomJS(
# args=dict(
# scatter=source_scatter,
# coeffs=source_coeffs,
# xy_value=source_xy_value,
# y_axis=fig.yaxis[0],
# ),
# code="""
# let currentSelect = this.value;
# let xyValueData = xy_value.data;
# let scatterData = scatter.data;
# let coeffsData = coeffs.data;
# xyValueData['y'][0] = currentSelect;
# scatterData['__y__'] = scatterData[currentSelect];
# coeffsData['__x__'] = coeffsData[`${xyValueData['x'][0]}${currentSelect}x`];
# coeffsData['__y__'] = coeffsData[`${xyValueData['x'][0]}${currentSelect}y`];
# y_axis.axis_label = currentSelect;
# scatter.change.emit();
# coeffs.change.emit();
# xy_value.change.emit();
# """,
# ),
# )
# fig = column(
# row(x_select, y_select, align="center"), fig, sizing_mode="stretch_width"
# )
# return fig