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()
def generate_users_bar(current_user_source): users_bar = Bar(current_user_source,values="editions",xlabel = None,ylabel = None,label="users",stack="edited",legend = None,title = "Editions for users",name ="Editions for users",tools = tools, width = 1000,height = 400) hover = users_bar.select(dict(type=HoverTool)) hover.tooltips = [ ('User','$x'), ('Page','@edited'), ('Editions','@height')] users_bar.background_fill_color = "#2f2f2f" users_bar.border_fill_color = "#2f2f2f" return users_bar
def test_bar_chart_below_visibility(): from bkcharts import Bar # Visible because we have multiple bars df = dict(types=['foo', 'bar'], counts=[3, 2]) p = Bar(df, values='counts') p.below[0].visible # Visible because we excplicitly specify labels df = dict(types=['foo'], counts=[3]) p = Bar(df, values='counts', label='types') assert p.below[0].visible # Not visible because only one item and no labels df = dict(types=['foo'], counts=[3]) p = Bar(df, values='counts') assert not p.below[0].visible
def create_bar(self): #Here, we interact with bokeh to create the bar chart. We use the dataframe we created above, set birth to the values on the y-axis and stack the data by sex. #The x axis label is represented by the areas. We define hover over the tooltips and define Gender and Births, with the corresponding value of the y axis. #Last but not least, we colour the data with always coloring female red and male blue. bar = Bar( self._dataframe, values='Births', label='Area', stack="Sex", agg="mean", title="Births in Zurich, 2015 per Area", legend='top_right', height=450, width=1050, tooltips=[('Gender:', '@Sex'), ('Births:', '@height')], palette=["#cc3737", "#0053d8"] ) #we return the bar to plot in on the Dashboard class return bar
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()
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))
def createFigure1(self): #Plot 1: Births in 2015 per gender births_2015 = pd.DataFrame(self.data.loc[self.data['Jahr'] == 2015], copy=True) # Removing the unnecessary columns births_2015 = births_2015.drop("SexCd", axis=1) births_2015 = births_2015.drop("StatZoneSort", axis=1) births_2015 = births_2015.drop("QuarSort", axis=1) #X-Axis Values: The names of the different parts of the city of Zurich quartier_names = [] for name in births_2015['Quartier']: if name not in quartier_names: quartier_names.append(name) quartier_names.sort() #Y-Axis Values: Nr of Births (male & female) per city part in 2015 births = pd.DataFrame(births_2015, copy=True) births = births.drop("Jahr", axis=1) births = births.groupby(['Sex', 'Quartier'])['Births'].sum().reset_index() colors = ["#e84d60", "#718dbf"] #Creating the vertical stacked bar chart self.plot1 = Bar( births, label='Quartier', stack='Sex', values='Births', title= 'Aggregated Number of Births per City Part (Quartier) in 2015', color=colors, ) # Designing the plot (legend, axis alignment & spacing) self.plot1.width = 1800 self.plot1.height = 450 self.plot1.legend.location = "top_right" self.plot1.legend.orientation = "horizontal" #X-Axis design self.plot1.xaxis.major_label_orientation = 0.3 self.plot1.x_range.range_padding = 0.05 self.plot1.xgrid.grid_line_color = None self.plot1.xaxis.axis_label = 'City Parts in Zurich' #Y-Axis design self.plot1.y_range.start = 0 self.plot1.yaxis[0].ticker.max_interval = 50 self.plot1.yaxis[0].ticker.num_minor_ticks = 0 self.plot1.yaxis.axis_label = 'Number of Births' #Creating the hover tooltip hover = HoverTool( tooltips=[("Quartier", "@Quartier"), ("Sex", "@Sex"), ("Births", "@height")]) self.plot1.tools.append(hover)
# transform ColumnDataFrame to ColumnDataSource tax_increase = ColumnDataSource( pd.DataFrame(df_dropped["Tax Units with Tax Increase"])) tax_cut = ColumnDataSource(pd.DataFrame(df_dropped["Tax Units with Tax Cut"])) cds_df_dropped = ColumnDataSource(df_dropped) # the plots with the bars p = Bar( df_dropped, 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=450, toolbar_sticky=False, legend=False) p.xaxis.axis_label = 'Income [$ thousands]' p.toolbar.logo = None values = blend('Tax Units with Tax Increase', 'Tax Units with Tax Cut', name='values', labels_name='vars')
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)
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) # Create the "Average tax" figure s1 = figure(plot_width=600, plot_height=200,
from bkcharts import Bar, output_file, show, defaults from bokeh.layouts import gridplot from bokeh.sampledata.autompg import autompg as df df['neg_mpg'] = 0 - df['mpg'] defaults.plot_width = 400 defaults.plot_height = 400 bar_plot = Bar(df, label='cyl', title="label='cyl'") bar_plot.title.text_font_size = '10pt' bar_plot2 = Bar(df, label='cyl', bar_width=0.4, title="label='cyl' bar_width=0.4") bar_plot2.title.text_font_size = '10pt' bar_plot3 = Bar(df, label='cyl', values='mpg', agg='mean', title="label='cyl' values='mpg' agg='mean'") bar_plot3.title.text_font_size = '10pt' bar_plot4 = Bar(df, label='cyl', title="label='cyl' color='DimGray'", color='dimgray') bar_plot4.title.text_font_size = '10pt'