def hotmap(datetime, room, query): """Generates a heatmap bokeh model""" #IMPORTANT: this query returns M-F values # get a df with date and count values, for a given room and date week_counts = pd.read_sql_query(query.format(date=datetime, room=room), connectDB()) headcount = list(week_counts['count']) headcount = [linear_predictor(x) for x in headcount] # predict on all supplied values bins = list(week_counts['count']) # bins = [tertiary_classifier(x) for x in bins] # predict on all supplied values tert_dictionary = { 'Empty': 0, 'Medium': 0.5, 'High': 1 } # map to int as only ints can go in heatmap # bins = [tert_dictionary[x] for x in bins] # map with listcomp # 5 * 9 = 45, so all elements need to have 45 values. Days and hours are just multipled out. data = { 'days': ['fri'] * 9 + ['thu'] * 9 + ['wed'] * 9 + ['tue'] * 9 + ['mon'] * 9, 'occupancy': headcount, 'hours': ['9', '10', '11', '12', '13', '14', '15', '16', '17'] * 5 } week_counts['headcount'] = week_counts['count'].apply(linear_predictor) week_counts['bins'] = week_counts['count'].apply(tertiary_classifier) source = ColumnDataSource(ColumnDataSource.from_df(week_counts)) # hover = HoverTool() # # tooltips = [("headcount", "@headcount")] # # tools = [hover] # colors = ['#1abc9c', '#ec583a', '#474e5d'] # set colors; currently not shading on continuous features hm = HeatMap(data, x='hours', y='days', values='occupancy', title='Occupancy in room over the week'.format(room), stat=None, palette=palette, tools=None, hover_tool=True) legend = Legend(location=(0, -30)) hm.add_layout(legend, 'right') all_plots = gridplot([[hm]]) return all_plots
from bokeh.charts import HeatMap, bins, output_file, show from bokeh.palettes import RdBu, magma from bokeh.models import ColumnDataSource, LabelSet, Label output_file("index.html", title="BTC premia") dateToDisplay = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") custompalette = ['#00814c', '#1ebd7c', '#26cc88', '#3ee09e', '#71ffc5', 'grey','#fcffc8', '#ffeb66', '#ffca49', '#ff9600', '#d00031'] hm1 = HeatMap(prem_last, x='from', y='to', values='diff', title=dateToDisplay+' Premia Last Closing (USD). diff = from - to, % = (from - to)/to', stat=None, palette=custompalette, legend=False) source1 = ColumnDataSource(data=prem_last) #labels1a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source1, text_font_size='9pt') labels1b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source1, text_font_size='9pt') #hm1.add_layout(labels1a) hm1.add_layout(labels1b) hm2 = HeatMap(prem_7day, x='from', y='to', values='diff', title=dateToDisplay+' Premia 7 days average (USD)', stat=None, palette=custompalette, legend=False) source2 = ColumnDataSource(data=prem_7day) #labels2a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source2, text_font_size='9pt') labels2b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source2, text_font_size='9pt') #hm2.add_layout(labels2a) hm2.add_layout(labels2b) hm3 = HeatMap(prem_30day, x='from', y='to', values='diff', title=dateToDisplay+' Premia 30 days average (USD)', stat=None, palette=custompalette, legend=False) source3 = ColumnDataSource(data=prem_30day) #labels3a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source3, text_font_size='9pt') labels3b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source3, text_font_size='9pt') #hm3.add_layout(labels3a) hm3.add_layout(labels3b)
prem_7day = calcMatrixHeatMap(rolling_7day) prem_30day = calcMatrixHeatMap(rolling_30day) from bokeh.layouts import row from bokeh.plotting import figure, show, output_file from bokeh.charts import HeatMap, bins, output_file, show from bokeh.palettes import RdBu, magma from bokeh.models import ColumnDataSource, LabelSet, Label output_file("ccy-premium.html", title="BTC premia") hm1 = HeatMap(prem_last, x='from', y='to', values='diff', title='Premia Last Closing (USD). diff = from - to, % = (from - to)/to', stat=None, palette=['green', 'gray', 'red'], legend=False) source1 = ColumnDataSource(data=prem_last) labels1a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source1) labels1b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-30, render_mode='canvas', source=source1) hm1.add_layout(labels1a) hm1.add_layout(labels1b) hm2 = HeatMap(prem_7day, x='from', y='to', values='diff', title='Premia 7 days average (USD)', stat=None, palette=['green', 'gray', 'red'], legend=False) source2 = ColumnDataSource(data=prem_7day) labels2a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source2) labels2b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-30, render_mode='canvas', source=source2) hm2.add_layout(labels2a) hm2.add_layout(labels2b) hm3 = HeatMap(prem_30day, x='from', y='to', values='diff', title='Premia 30 days average (USD)', stat=None, palette=['green', 'gray', 'red'], legend=False) source3 = ColumnDataSource(data=prem_30day) labels3a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source3) labels3b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-30, render_mode='canvas', source=source3) hm3.add_layout(labels3a) hm3.add_layout(labels3b)
# hm10 = HeatMap(unempl, x='Year', y='Month', values='Unemployment', stat=None, # sort_dim={'x': False}, width=900, plot_height=500) TOOLS = [BoxSelectTool(), HoverTool()] hm11 = HeatMap(test, x='region', y='area', values='data', legend=False, stat=None, palette=GnRd9, width = 500, plot_height=500, title="Actlab Region Detection Test", tools=TOOLS) hm12 = Bar(data_bar, values='dist', label='region', legend=False, title='Error Distance for Respective Regions', width = 800, plot_height = 500) hm13 = BoxPlot(data_bar, values='dist', label='region', legend=False, title='Error Distance Boxplot', width = 300, plot_height=300) #hm11.legend.location = 'right' # data1 = [int(x) for x in data] # print data1 # hover = HoverTool(tooltips=[ # ("error", "@data1")]) # hm11.add_tools(hover) hm11.add_layout(labels) hm11.add_layout(labels_dev) hm12.add_layout(label_reg) # output_file("heatmap.html") output_file("Bar.html") hm11.axis.visible = False # show(hm11) # show(hm12) # show(hm13) show(column( gridplot(hm11, hm12, ncols=1, plot_width=400, plot_height=400) ))
def bokeh_heatmap(index=['Date', 'Representative']): #return three retention matrices percent_MRR, actual_MRR, contract_MRR = pivot_tables(combo=generate_data( n_sample=100, periods=30), index=index) #reformat data to column sparse matrix and place into dictionary x = [] y = [] vals = [] [(y.append(i[0]), x.append(i[1]), vals.append(v)) for i, v in np.ndenumerate(percent_MRR)] data = {'x': x, 'y': y, 'vals': vals} #heatmap instantiate hm = HeatMap(data=data, x='x', y='y', values='vals', stat=None, title='Revenue Retention by {}'.format(','.join(index)), ygrid=True, xgrid=True, xlabel='months', ylabel='contract start', yscale='categorical', palette=brewer['RdYlGn'][11], title_text_font_size='20pt') #add value labels to heat map # create formatted column of values for annotation labels data['labels'] = [ '{:.0%}'.format(round(i, 2)) if i >= 0 else '' for i in data['vals'] ] #dropping vals which are not json compliant del data['vals'] source = ColumnDataSource(data=data) labels = LabelSet(x='x', y='y', text='labels', level='glyph', x_offset=-2, y_offset=-4, source=source, render_mode='canvas', text_font_size='7pt', text_color='white') hm.add_layout(labels) # customize y-axis text # new_index=actual_MRR.sum(axis=1).reset_index() # new_index.rename(columns={0: 'Actual MRR'}, inplace=True) # new_index['Contract MRR']=contract_MRR.sum(axis=1).reset_index()[0] y_label_dict = {} for index, groups in enumerate(list(percent_MRR.index)): y_label_dict[index] = '-'.join(groups) #reverse y-axis order hm.y_range.start = max(y_label_dict.keys()) hm.y_range.end = min(y_label_dict.keys()) hm.x_range = Range1d(0, 12) #generate javascript code to reformat y-axis hm.yaxis.formatter = FuncTickFormatter(code="""var labels = {}; return labels[tick]; """.format(y_label_dict)) # fix ticks to display all values hm.yaxis[0].ticker = FixedTicker(ticks=list(y_label_dict.keys())) total_contract_mrr = contract_MRR.sum(axis=1) total_actual_mrr = actual_MRR.sum(axis=1) yaxis2_text = pd.concat([total_actual_mrr, total_contract_mrr], axis=1) yaxis2_text.reset_index(drop=True, inplace=True) yaxis2_text.columns = ['Actual MRR', 'Contract MRR'] yaxis2_text['text'] = yaxis2_text.apply( lambda row: '{:,.0f}/{:,.0f} \t ({:.0%})'.format( row['Actual MRR'], row['Contract MRR'], row['Actual MRR'] / row[ 'Contract MRR']), axis=1) yaxis2_text = yaxis2_text['text'].to_dict() #add right hand y-axis for additional information top = max(yaxis2_text.keys()) bottom = min(yaxis2_text.keys()) print(top, bottom) hm.extra_y_ranges = {'mrr': Range1d(top, bottom)} hm.add_layout(LinearAxis(y_range_name="mrr"), 'right') hm.yaxis[1].formatter = FuncTickFormatter(code="""var labels = {}; return labels[tick]; """.format(yaxis2_text)) hm.yaxis[1].ticker = FixedTicker(ticks=list(yaxis2_text.keys())) hm.yaxis[1].axis_label = 'Actual and Contract MRR' hm.yaxis[1].major_label_standoff = 30 # #help(hm.legend) # legend_items=list(hm.legend)[0].items # hm.legend.location = 'bottom_right' # exit() output_file('interactive.html') show(hm)
from bokeh.layouts import row from bokeh.plotting import figure, show, output_file from bokeh.charts import HeatMap, bins, output_file, show from bokeh.palettes import RdBu, magma from bokeh.models import ColumnDataSource, LabelSet, Label output_file("ccy-premium.html", title="BTC premia") dateToDisplay = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") hm1 = HeatMap(prem_last, x='from', y='to', values='diff', title=dateToDisplay+' Premia Last Minute Closing (USD). diff = from - to, % = (from - to)/to', stat=None, palette=['green', 'gray', 'red'], legend=False) source1 = ColumnDataSource(data=prem_last) labels1a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source1) labels1b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-30, render_mode='canvas', source=source1) hm1.add_layout(labels1a) hm1.add_layout(labels1b) hm2 = HeatMap(prem_7day, x='from', y='to', values='diff', title=dateToDisplay+' Premia Last 10 minutes average (USD)', stat=None, palette=['green', 'gray', 'red'], legend=False) source2 = ColumnDataSource(data=prem_7day) labels2a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source2) labels2b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-30, render_mode='canvas', source=source2) hm2.add_layout(labels2a) hm2.add_layout(labels2b) hm3 = HeatMap(prem_30day, x='from', y='to', values='diff', title=dateToDisplay+' Premia last 60 minutes average (USD)', stat=None, palette=['green', 'gray', 'red'], legend=False) source3 = ColumnDataSource(data=prem_30day) labels3a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source3) labels3b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-30, render_mode='canvas', source=source3) hm3.add_layout(labels3a) hm3.add_layout(labels3b)
stat=None, palette=custompalette, legend=False) source1 = ColumnDataSource(data=prem_last) #labels1a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source1, text_font_size='9pt') labels1b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source1, text_font_size='9pt') #hm1.add_layout(labels1a) hm1.add_layout(labels1b) hm2 = HeatMap(prem_7day, x='from', y='to', values='diff', title=dateToDisplay + ' Premia 7 days average (USD)', stat=None, palette=custompalette, legend=False) source2 = ColumnDataSource(data=prem_7day) #labels2a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-10, y_offset=-10, render_mode='canvas', source=source2, text_font_size='9pt') labels2b = LabelSet(x='from', y='to', text='percent', level='glyph',
legend=False, title='Nlsql_y2 Latitude Boxplot', width=550, plot_height=600) hm24 = BoxPlot(box_y2lng, values='Error Distance', label='Devices', legend=False, title='Nlsql_y2 Longtitude Boxplot', width=550, plot_height=600) refresh = Button(label="Refresh", button_type="success") refresh.on_click(callback) hm11.add_layout(labels_cal) hm11.add_layout(labels_dev1) hm14.add_layout(labels_bary) hm14.add_layout(labels_dev2) hm15.add_layout(labels_oys) hm15.add_layout(labels_dev3) hm16.add_layout(labels_y2) hm16.add_layout(labels_dev4) # output_file("Heatmap.html") hm11.axis.visible = False hm14.axis.visible = False hm15.axis.visible = False hm16.axis.visible = False widgetrow = row(select1, refresh)