def get_plot_comp(df, player_name): values = blend( 'pass', 'shoot', 'turnover', name='action probability', labels_name='play_action' ) labels = cat(columns='region', sort=False) stacks = cat(columns='play_action', sort=False) colors = color( columns='play_action', palette=['DeepSkyBlue', 'LightGreen', 'LightPink'], sort=False ) title = player_name + ' Action Probability per Region' hover_info = [('action', '@play_action'), ('prob', '@height')] bar = Bar( df, values=values, label=labels, stack=stacks, color=colors, legend='bottom_left', title=title, tooltips=hover_info ) bar.title.text_font_size = '14pt' bar.legend.orientation = 'horizontal' script, div = components(bar) # output_file("~/repos/Triple-Triple/triple_triple/simulator_analytics/plot_app/templates/test_bar.html") return script, div, bar
def update_plot(attrname, old, new): form = form_select.value[-1:] cols = [] for techs in range(1, self.n_techs + 1): cols.append('n' + str(techs) + str(form)) tbar = Bar( cap_source, values=blend(*cols, name='medals', labels_name='medal'), label='n_list', stack='medal', legend=None, color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), title="Energy Capacity per Node for Each Form of Energy", plot_width=1000, plot_height=300, xlabel="Nodes", ylabel="Storage Capacity(kW)") hover = HoverTool(tooltips=[ ("Node", "@n_list"), ("Value", "@height"), ]) tbar.add_tools(hover) disp_row_1.children[0] = tbar fin_column.children[1] = self.create_legend()
def update_plotw(attrname, old, new): node = node_selectw.value[-1:] form = form_selectw.value[-1:] cols = [] for techs in range(1, self.n_techs + 1): cols.append('n' + str(node) + str(form) + str(techs)) print('n' + str(node) + str(form) + str(techs)) pbarw = Bar( prod_dataw, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Energy Production per Node for Each Form of Energy", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Weeks", ylabel="Energy Production(kW)") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) pbarw.add_tools(hover) disp_row_2.children[0] = pbarw fin_column.children[1] = self.create_legend()
# add the year as text plot text_source = ColumnDataSource({'year': ['%s' % years[0]]}) text = Text(x=0.8, y=600, text='year', text_font_size='20pt', text_color='#0569CE', text_alpha=1) #add the Bar graph p = Bar( renderer_source.data, label=cat(columns='Intervals', sort=False), values=blend('Tax Units with Tax Increase', 'Tax Units with Tax Cut', name='values', labels_name='vars'), tooltips=[('Value', '@values')], ylabel="Tax units with tax cut Tax units with tax increase", stack=cat(columns='values', sort=False), color=color(columns='vars', palette=['silver', 'orange'], sort=True), bar_width=0.4, tools="pan,box_zoom, reset, save", plot_width=600, plot_height=500, logo=None, toolbar_sticky=False, legend=False) p.xaxis.axis_label = 'Income [$ thousands]' #add the text as a glyph p.add_glyph(text_source, text)
scatter3 = Scatter( df, x='mpg', y='hp', color='origin', title="x='mpg', y='hp', color='origin', with tooltips", xlabel="Miles Per Gallon", ylabel="Horsepower", legend='top_right', tooltips=tooltips) scatter4 = Scatter( df, x='mpg', y='hp', color='cyl', marker='origin', title="x='mpg', y='hp', color='cyl', marker='origin'", xlabel="Miles Per Gallon", ylabel="Horsepower", legend='top_right', tooltips=tooltips) # Example with nested json/dict like data, which has been pre-aggregated and pivoted df2 = df_from_json(data) df2 = df2.sort_values(by='total', ascending=False) df2 = df2.head(10) df2 = pd.melt(df2, id_vars=['abbr', 'name']) scatter5 = Scatter( df2, x='value', y='name', color='variable', title="x='value', y='name', color='variable'", xlabel="Medals", ylabel="Top 10 Countries", legend='bottom_right') scatter6 = Scatter(flowers, x=blend('petal_length', 'sepal_length', name='length'), y=blend('petal_width', 'sepal_width', name='width'), color='species', title='x=petal_length+sepal_length, y=petal_width+sepal_width, color=species', legend='top_right') output_file("scatter_multi.html", title="scatter_multi.py example") show(gridplot(scatter0, scatter2, scatter3, scatter4, scatter5, scatter6, ncols=2))
""" This example uses the Iris data to demonstrate the specification of combined variables using chart operations. This specific instance uses a blend, which stacks columns, and renames the combined column. This can be used where the column itself is a type of categorical variable. Here, length and width are derived from the petal and sepal measurements. """ from bkcharts import Scatter, output_file, show from bkcharts.operations import blend from bokeh.sampledata.iris import flowers as data scatter = Scatter(data, x=blend('petal_length', 'sepal_length', name='length'), y=blend('petal_width', 'sepal_width', name='width'), color='species', title='x=petal_length+sepal_length, y=petal_width+sepal_width, color=species', legend='top_right') output_file("iris_blend.html", title="iris_blend.py example") show(scatter)
def carbon_emissions(self): c_em_tech = {} c_em_tech['time_step'] = np.linspace(1, self.time_steps, self.time_steps) for techs in range(1, self.n_techs + 1): c_em_tech['t' + str(techs)] = np.zeros((self.time_steps)) for time_step in range(1, self.time_steps): c_em_tech['t' + str(techs)][time_step] = value( model.carbonFactors[techs] * sum(model.P[i, time_step, techs] for i in model.hub_i)) cols = [] for techs in range(1, self.n_techs + 1): cols.append('t' + str(techs)) bar = Bar(c_em_tech, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Carbon Emissions per form of Technology", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Hours", ylabel="Carbon Emissions(kg)") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) bar.add_tools(hover) tech_legend1 = self.create_legend() c_em_techw = {} if (self.time_weeks == 0): for k, v in c_em_tech.items(): c_em_techw[k] = np.zeros((1)) c_em_techw['time_step'] = np.zeros((1)) else: for k, v in c_em_tech.items(): v = v[:self.time_weeks * self.week_h] c_em_techw[k] = np.sum(v.reshape(-1, self.week_h), axis=1) c_em_techw['time_step'] = np.linspace(1, self.time_weeks, self.time_weeks) bar_w = Bar(c_em_techw, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Carbon Emissions per form of Technology per Week", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Weeks", ylabel="Carbon Emissions(kg)") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) c_em_nodes = {} c_em_nodes['time_step'] = np.linspace(1, self.time_steps, self.time_steps) for hub_step in range(1, self.n_hubs + 1): c_em_nodes['n' + str(hub_step)] = np.zeros((self.time_steps)) for time_step in range(1, self.time_steps): c_em_nodes['n' + str(hub_step)][time_step] = value( sum(model.carbonFactors[inp] * model.P[hub_step, time_step, inp] for inp in model.In)) col_nodes = [] for hubs in range(1, self.n_hubs + 1): col_nodes.append('n' + str(hubs)) if (self.n_hubs == 1): hub_colour = ["red"] elif (self.n_hubs == 2): hub_colour = ["red", "blue"] else: hub_colour = brewer['Set1'][self.n_hubs] n_bar = Bar(c_em_nodes, values=blend(*col_nodes, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Carbon Emissions per Node", color=color(columns='medal', palette=hub_colour, sort=True), plot_width=1000, plot_height=300, xlabel="Nodes", ylabel="Carbon Emissions(kg)") n_hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) n_bar.add_tools(n_hover) y = [0] * len(self.nodes) x = self.nodes #pal = ['SaddleBrown', 'Silver', 'Goldenrod'] node_legend = figure(width=1000, height=50, toolbar_location=None, active_drag=None, x_range=self.nodes) node_legend.rect(x, y, color=hub_colour, width=1, height=10) node_legend.yaxis.major_label_text_color = None node_legend.yaxis.major_tick_line_color = None node_legend.yaxis.minor_tick_line_color = None return column(bar, tech_legend1, bar_w, n_bar, node_legend)
def costs(self): op_cost = model.OpCost.get_values()[None] opcost_dict = {} opcost_dict.update( (x, y * op_cost) for x, y in model.P.get_values().items()) opcost_data = {} for techs in range(1, self.n_techs + 1): opcost_data['t' + str(techs)] = np.zeros((self.time_steps)) for time_step in range(1, self.time_steps): for hub_step in range(1, self.n_hubs + 1): opcost_data['t' + str(techs)][time_step] += opcost_dict[( hub_step, time_step, techs)] opcost_data['time_step'] = np.linspace(1, self.time_steps, self.time_steps) cols = [] for techs in range(1, self.n_techs + 1): cols.append('t' + str(techs)) opcost_bar = Bar(opcost_data, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Operational Cost per form of Technology", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Hours", ylabel="CHF") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) opcost_bar.add_tools(hover) tech_legend1 = self.create_legend() opcost_dataw = {} if (self.time_weeks == 0): for k, v in opcost_data.items(): opcost_dataw[k] = np.zeros((1)) opcost_dataw['time_step'] = np.zeros((1)) else: for k, v in opcost_data.items(): v = v[:self.time_weeks * self.week_h] print(v[:self.time_weeks * self.week_h]) opcost_dataw[k] = np.sum(v.reshape(-1, self.week_h), axis=1) opcost_dataw['time_step'] = np.linspace(1, self.time_weeks, self.time_weeks) opcostbar_w = Bar( opcost_dataw, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Operational Cost per form of Technology per Week", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Hours", ylabel="CHF") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) mtc_cost = data.VarMaintCost() P = model.P.get_values() for hub_step in range(1, self.n_hubs + 1): for techs in range(1, self.n_techs + 1): for time_step in range(1, self.time_steps): P[(hub_step, time_step, techs)] *= mtc_cost[(hub_step, techs)] mtccost_data = {} for techs in range(1, self.n_techs + 1): mtccost_data['t' + str(techs)] = np.zeros((self.time_steps)) for time_step in range(1, self.time_steps): for hub_step in range(1, self.n_hubs + 1): mtccost_data['t' + str(techs)][time_step] += P[(hub_step, time_step, techs)] mtccost_data['time_step'] = np.linspace(1, self.time_steps, self.time_steps) mtccost_bar = Bar(mtccost_data, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Maintenance Cost per form of Technology", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Hours", ylabel="CHF") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) mtccost_bar.add_tools(hover) opc = model.OpCost.get_values()[None] mtc = model.MaintCost.get_values()[None] inc = model.InvCost.get_values()[None] income = model.IncomeExp.get_values()[None] sum_pi = opc + mtc + inc + income values = [opc, mtc, inc, income] percents = [ 0, opc / sum_pi, (opc + mtc) / sum_pi, (opc + mtc + inc) / sum_pi, (opc + mtc + inc + income) / sum_pi ] starts = [p * 2 * np.pi for p in percents[:-1]] ends = [p * 2 * np.pi for p in percents[1:]] colors = brewer["Set1"][4] cost_labels = [ "Operational Cost", "Maintenance Cost", "Investment Cost", "Income" ] pie_chart_source = ColumnDataSource(data=dict(x=[0 for x in percents], y=[0 for x in percents], percents=percents, starts=starts, colors=colors, ends=ends, values=values, cost_labels=cost_labels)) pie_chart = figure(title="Cost vs Income Breakdown", plot_width=500, plot_height=300, toolbar_location="left") r = pie_chart.wedge(source=pie_chart_source, x='x', y='y', alpha=0.8, radius=0.8, start_angle='starts', end_angle='ends', color='colors') legend = Legend( items=[LegendItem(label=dict(field="cost_labels"), renderers=[r])], location=(0, -50)) pie_chart.add_layout(legend, 'right') hover = HoverTool(tooltips=[ ("Type", "@cost_labels"), ("Value", "@values"), ]) pie_chart.add_tools(hover) pie_chart.xaxis.visible = False pie_chart.xgrid.visible = False pie_chart.yaxis.visible = False pie_chart.ygrid.visible = False op_column = column(opcost_bar, tech_legend1, opcostbar_w, mtccost_bar, pie_chart) return op_column
def capacities(self): cap_source = {} for techs in range(1, self.n_techs + 1): for forms in range(1, self.n_forms + 1): cap_source['n' + str(techs) + str(forms)] = np.zeros( (self.n_hubs)) for hub_step in range(1, self.n_hubs + 1): cap_source['n' + str(techs) + str(forms)][hub_step - 1] = self.cap_dict[(hub_step, techs, forms)] #cap_source['n' + str(techs) + str(forms)] = np.array(cap_source['n' + str(techs) + str(forms)]) # for forms in range(1,self.n_forms+1): # cap_source['n' + str(self.n_techs+2) + str(forms)] = np.zeros((self.n_hubs)) # for hub_step in range(1,self.n_hubs+1): # for techs in range(1,self.n_techs+1): # cap_source['n' + str(self.n_techs+2) + str(forms)][hub_step-1] += cap_source['n' + str(techs) + str(forms)][hub_step-1] # # cap_source['n_list'] = [] # for hub_step in range(1,self.n_hubs+1): # cap_source['n_list'].append( "Node " + str(hub_step)) cap_source['n_list'] = self.nodes #cap_source['n21'] = np.array([34.8,78,54,12,90]) cols = [] for techs in range(1, self.n_techs + 1): cols.append('n' + str(techs) + str(1)) v_bar = Bar(cap_source, values=blend(*cols, name="medal_v", labels_name="medals"), label='n_list', stack='medals', legend=None, color=color(columns='medals', palette=brewer['Set1'][self.n_techs], sort=True), title="Energy Capacity per Node for Each Technology", plot_width=1000, plot_height=300, xlabel="Nodes", ylabel="Energy Capacity(kW)") hover = HoverTool(tooltips=[ ("Node", "@n_list"), ("Value", "@height"), ]) v_bar.add_tools(hover) def update_plot(attrname, old, new): form = form_select.value[-1:] cols = [] for techs in range(1, self.n_techs + 1): cols.append('n' + str(techs) + str(form)) tbar = Bar( cap_source, values=blend(*cols, name='medals', labels_name='medal'), label='n_list', stack='medal', legend=None, color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), title="Energy Capacity per Node for Each Form of Energy", plot_width=1000, plot_height=300, xlabel="Nodes", ylabel="Storage Capacity(kW)") hover = HoverTool(tooltips=[ ("Node", "@n_list"), ("Value", "@height"), ]) tbar.add_tools(hover) disp_row_1.children[0] = tbar fin_column.children[1] = self.create_legend() form_select = Select(value="Form1", title='Forms', options=self.e_forms) form_select.on_change('value', update_plot) tech_legend1 = self.create_legend() storage = model.StorageCap.get_values() print(storage) storage_dict = {} storage_dict['n_list'] = self.nodes for forms in range(1, self.n_forms + 1): storage_dict['f' + str(forms)] = np.zeros((self.n_hubs)) for hub_step in range(1, self.n_hubs + 1): storage_dict['f' + str(forms)][hub_step - 1] = storage[(hub_step, forms)] # storage_dict['f1'] = [23,67,98,41,11] storage_bar = Bar(storage_dict, values='f1', label='n_list', legend=None, title="Storage Capacity per Node", plot_width=1000, plot_height=300, xlabel="Nodes", ylabel="Storage Capacity(kW)") hover = HoverTool(tooltips=[ ("Node", "@n_list"), ("Value", "@height"), ]) def update_plot_st(attrname, old, new): form = form_select_st.value[-1:] st_bar = Bar(storage_dict, values='f' + str(form), label='n_list', legend=None, title="Storage Capacity per Node", plot_width=1000, plot_height=300, xlabel="Nodes", ylabel="Storage Capacity(kW)") hover = HoverTool(tooltips=[ ("Node", "@n_list"), ("Value", "@height"), ]) st_bar.add_tools(hover) disp_row_2.children[0] = st_bar fin_column.children[1] = self.create_legend() form_select_st = Select(value="Form1", title='Forms', options=self.e_forms) form_select_st.on_change('value', update_plot_st) gis_dict = {} gis_dict['x'] = 14 * np.random.rand(self.n_hubs, ) gis_dict['y'] = 6 * np.random.rand(self.n_hubs, ) if (self.n_hubs == 1): x_range = (0, gis_dict['x'].max()) y_range = (0, gis_dict['y'].max()) else: x_range = (gis_dict['x'].min(), gis_dict['x'].max()) y_range = (gis_dict['y'].min(), gis_dict['y'].max()) gis_plot = figure(title="Node Locations with Capacities", plot_width=600, plot_height=600, x_range=x_range, y_range=y_range) gis_plot.xaxis.axis_label = "X Coordinates" gis_plot.yaxis.axis_label = "Y Coordinates" for k, v in cap_source.items(): gis_dict[k] = v if (k != 'n_list' and v.max(axis=0) != 0): gis_dict[k + 'n'] = v / v.max(axis=0) * abs(max(y_range) * 3) else: gis_dict[k + 'n'] = gis_dict[k] gis_dict['temp'] = gis_dict['n11'] gis_dict['tempn'] = gis_dict['n11n'] gis_source = ColumnDataSource(data=gis_dict) gis_plot.circle( x='x', y='y', radius='tempn', source=gis_source, radius_dimension='y', radius_units='screen', ) gis_hover = HoverTool(tooltips=[("X", "@x"), ("Y", "@y"), ("Value", "@temp")]) gis_plot.add_tools(gis_hover) def update_plot_gis(attrname, old, new): form = form_select_gis.value[-1:] tech = tech_select_gis.value[-1:] gis_source.data['temp'] = gis_source.data['n' + str(tech) + str(form)] gis_source.data['tempn'] = gis_source.data['n' + str(tech) + str(form) + 'n'] form_select_gis = Select(value="Form1", title='Forms', options=self.e_forms) tech_select_gis = Select(value="Tech1", title='Technologies', options=self.e_techs) form_select_gis.on_change('value', update_plot_gis) tech_select_gis.on_change('value', update_plot_gis) controls = column(form_select) controls_2 = column(form_select_st) controls_3 = column(form_select_gis, tech_select_gis) disp_row_1 = row(v_bar, controls) disp_row_2 = row(storage_bar, controls_2) disp_row_3 = row(gis_plot, controls_3) fin_column = column(disp_row_1, tech_legend1, disp_row_2, disp_row_3) return fin_column
def production(self): prodmat = {} for hub_step in range(1, self.n_hubs + 1): for time_step in range(1, self.time_steps + 1): for forms in range(1, self.n_forms + 1): for techs in range(1, self.n_techs + 1): prodmat[(hub_step, time_step, forms, techs)] = self.demand[(hub_step, time_step, forms)] * self.cmatrix[ (techs, forms)] prod_data = {} for hub_step in range(1, self.n_hubs + 1): for forms in range(1, self.n_forms + 1): for techs in range(1, self.n_techs + 1): prod_data['n' + str(hub_step) + str(forms) + str(techs)] = np.zeros((self.time_steps + 1)) for time_step in range(1, self.time_steps + 1): prod_data['n' + str(hub_step) + str(forms) + str(techs)][time_step] = prodmat[(hub_step, time_step, forms, techs)] prod_data['time_step'] = np.linspace(1, self.time_steps + 1, self.time_steps + 1) cols = [] for techs in range(1, self.n_techs + 1): cols.append('n' + str(11) + str(techs)) bar = Bar(prod_data, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Energy Production per Node for Each Form of Energy", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Hours", ylabel="Energy Production(kW)") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) bar.add_tools(hover) tech_legend1 = self.create_legend() prod_dataw = {} if (self.time_weeks == 0): for k, v in prod_data.items(): prod_dataw[k] = np.zeros((1)) prod_dataw['time_step'] = np.zeros((1)) else: for k, v in prod_data.items(): v = v[:self.time_weeks * self.week_h] prod_dataw[k] = np.sum(v.reshape(-1, self.week_h), axis=1) prod_dataw['time_step'] = np.linspace(1, self.time_weeks, self.time_weeks) bar_w = Bar( prod_dataw, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Energy Production per Node for Each Form of Energy per Week", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Weeks", ylabel="Energy Production(kW)") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) bar_w.add_tools(hover) def update_plot(attrname, old, new): node = node_select.value[-1:] form = form_select.value[-1:] cols = [] for techs in range(1, self.n_techs + 1): cols.append('n' + str(node) + str(form) + str(techs)) pbar = Bar( prod_data, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Energy Production per Node for Each Form of Energy", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Hours", ylabel="Energy Production(kW)") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) pbar.add_tools(hover) disp_row.children[0] = pbar def update_plotw(attrname, old, new): node = node_selectw.value[-1:] form = form_selectw.value[-1:] cols = [] for techs in range(1, self.n_techs + 1): cols.append('n' + str(node) + str(form) + str(techs)) print('n' + str(node) + str(form) + str(techs)) pbarw = Bar( prod_dataw, values=blend(*cols, name='medals', labels_name='medal'), label='time_step', stack='medal', legend=None, title="Energy Production per Node for Each Form of Energy", color=color(columns='medal', palette=brewer['Set1'][self.n_techs], sort=True), plot_width=1000, plot_height=300, xlabel="Weeks", ylabel="Energy Production(kW)") hover = HoverTool(tooltips=[ ("Hour", "@time_step"), ("Value", "@height"), ]) pbarw.add_tools(hover) disp_row_2.children[0] = pbarw fin_column.children[1] = self.create_legend() node_select = Select(value="Node1", title='Nodes', options=self.nodes) form_select = Select(value="Form1", title='Forms', options=self.e_forms) node_select.on_change('value', update_plot) form_select.on_change('value', update_plot) controls = column(node_select, form_select) disp_row = row(bar, controls) node_selectw = Select(value="Node1", title='Nodes', options=self.nodes) form_selectw = Select(value="Form1", title='Forms', options=self.e_forms) node_selectw.on_change('value', update_plotw) form_selectw.on_change('value', update_plotw) controlsw = column(node_selectw, form_selectw) disp_row_2 = row(bar_w, controlsw) fin_column = column(disp_row, tech_legend1, disp_row_2) return fin_column
def createBokehChart(self): keyFields = self.getKeyFields() valueFields = self.getValueFields() clusterby = self.options.get("clusterby") stacked = self.options.get("charttype", "grouped") == "stacked" subplots = self.isSubplot() workingPDF = self.getWorkingPandasDataFrame().copy() def convertPDFDate(df, col): #Bokeh doesn't support datetime as index in Bar chart. Convert to String if len(keyFields) == 1: dtype = df[col].dtype.type if col in df else None if numpy.issubdtype(dtype, numpy.datetime64): dateFormat = self.options.get("dateFormat", None) try: df[col] = df[col].apply( lambda x: str(x).replace(':', '-') if dateFormat is None else x.strftime(dateFormat)) except: self.exception("Error converting dateFormat {}".format( dateFormat)) df[col] = df[col].apply( lambda x: str(x).replace(':', '-')) for index, row in workingPDF.iterrows(): for k in keyFields: if isinstance(row[k], str if sys.version >= '3' else basestring): row[k] = row[k].replace(':', '.') workingPDF.loc[index] = row charts = [] def goChart(label, stack_or_group, values, ylabel=None, color=None): convertPDFDate(workingPDF, keyFields[0]) if ylabel is None: ylabel = values label = label if isinstance(label, (list, tuple)) else [label] if stacked: charts.append( Bar(workingPDF, label=CatAttr(columns=label, sort=False), stack=stack_or_group, color=color, values=values, legend=self.showLegend(), ylabel=ylabel)) else: charts.append( Bar(workingPDF, label=CatAttr(columns=label, sort=False), group=stack_or_group, color=color, values=values, legend=self.showLegend(), ylabel=ylabel)) if clusterby is not None and (subplots or len(valueFields) <= 1): subplots = subplots if len(valueFields) == 1 or subplots else False if subplots: for j, valueField in enumerate(valueFields): pivot = workingPDF.pivot(index=keyFields[0], columns=clusterby, values=valueField) for i, col in enumerate(pivot.columns[:10]): #max 10 data = pd.DataFrame({ 'values': pivot[col].values, 'names': pivot.index.values }) convertPDFDate(data, 'names') if subplots: charts.append( Bar(data, label=CatAttr(columns=['names'], sort=False), color=Colors.hexRGB(1. * i / 2), values='values', ylabel=valueField, legend=False, title="{0} = {1}".format( clusterby, pivot.columns[i]))) else: goChart(keyFields[0], clusterby, valueFields[0]) else: if subplots: for i, valueField in enumerate(valueFields): goChart(keyFields[0], None, valueField, color=Colors.hexRGB(1. * i / 2)) else: if len(valueFields) > 1: series = '_'.join(valueFields) values = blend(*valueFields, name=series.replace('_', ','), labels_name=series) else: series = False values = valueFields[0] goChart(keyFields, series, values, ylabel=','.join(valueFields)) if clusterby is not None: self.addMessage( "Warning: 'Cluster By' ignored when grouped option with multiple Value Fields is selected" ) return charts
from bkcharts import Bar, output_file, show from bkcharts.attributes import cat, color from bkcharts.operations import blend from bkcharts.utils import df_from_json from bokeh.sampledata.olympics2014 import data # utilize utility to make it easy to get json/dict data converted to a dataframe df = df_from_json(data) # filter by countries with at least one medal and sort by total medals df = df[df['total'] > 0] df = df.sort_values(by="total", ascending=False) bar = Bar(df, values=blend('bronze', 'silver', 'gold', name='medals', labels_name='medal'), label=cat(columns='abbr', sort=False), stack=cat(columns='medal', sort=False), color=color(columns='medal', palette=['SaddleBrown', 'Silver', 'Goldenrod'], sort=False), legend='top_right', title="Medals per Country, Sorted by Total Medals", tooltips=[('medal', '@medal'), ('country', '@abbr')]) output_file("stacked_bar.html", title="stacked_bar.py example") show(bar)