Python plotly.graph_objs.Bar() Examples

The following are 30 code examples of plotly.graph_objs.Bar(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module plotly.graph_objs , or try the search function .
Example #1
Source File: callret_analysis.py    From idasec with GNU Lesser General Public License v2.1 7 votes vote down vote up
def generate_chart(self, _):
        try:
            import plotly
            import plotly.graph_objs as go
            data = [[0, 0, 0], [0, 0, 0]]
            ok, viol = self.results.get_ok_viol()
            x = ["OK (%d)" % ok, "Tampering (%d)" % viol]
            for ret in self.results:
                i = 1 if ret.is_tampering() else 0
                data[i][0] += ret.is_aligned()
                data[i][1] += ret.is_disaligned()
                data[i][2] += ret.is_single()
            final_data = [go.Bar(x=x, y=[x[0] for x in data], name="Aligned"), go.Bar(x=x, y=[x[1] for x in data], name="Disaligned"), go.Bar(x=x, y=[x[2] for x in data], name="Single")]
            fig = go.Figure(data=final_data, layout=go.Layout(barmode='group', title='Call stack tampering labels'))
            plotly.offline.plot(fig, output_type='file', include_plotlyjs=True, auto_open=True)
        except ImportError:
            self.log("ERROR", "Plotly module not available") 
Example #2
Source File: d_energy_loss_bar.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        # calculate graph
        graph = []
        # format demand values
        P_loss_kWh = self.P_loss_kWh.fillna(value=0)
        P_loss_kWh = pd.DataFrame(P_loss_kWh.sum(axis=0), columns=['P_loss_kWh'])
        Q_loss_kWh = abs(self.thermal_loss_edges_kWh.fillna(value=0))
        Q_loss_kWh = pd.DataFrame(Q_loss_kWh.sum(axis=0), columns=['Q_loss_kWh'])
        # calculate total_df
        total_df = pd.DataFrame(P_loss_kWh.values + Q_loss_kWh.values, index=Q_loss_kWh.index, columns=['total'])
        # join dataframes
        merged_df = P_loss_kWh.join(Q_loss_kWh).join(total_df)
        merged_df = merged_df.sort_values(by='total',
                                          ascending=False)  # this will get the maximum value to the left

        # iterate through P_loss_kWh to plot
        for field in ['P_loss_kWh', 'Q_loss_kWh']:
            total_percent = (merged_df[field] / merged_df['total'] * 100).round(2)
            total_percent_txt = ["(" + str(x) + " %)" for x in total_percent]
            trace = go.Bar(x=merged_df.index, y=merged_df[field].values, name=NAMING[field],
                           text=total_percent_txt,
                           orientation='v',
                           marker=dict(color=COLOR[field]))
            graph.append(trace)
        return graph 
Example #3
Source File: test_vis.py    From IRCLogParser with GNU General Public License v3.0 6 votes vote down vote up
def test_generate_group_bar_charts(self, mock_py):
        x_values = [
            [5.10114882, 5.0194652482, 4.9908093076],
            [4.5824497358, 4.7083614037, 4.3812775722],
            [2.6839471308, 3.0441476209, 3.6403820447]
        ]
        y_values = ['#kubuntu-devel', '#ubuntu-devel', '#kubuntu']
        trace_headers = ['head1', 'head2', 'head3']
        test_data = [
            go.Bar(
                x=x_values,
                y=y_values[i],
                name=trace_headers[i]
            ) for i in range(len(y_values))
        ]

        layout = go.Layout(barmode='group')
        fig = go.Figure(data=test_data, layout=layout)
        vis.generate_group_bar_charts(y_values, x_values, trace_headers, self.test_data_dir, 'test_group_bar_chart')
        self.assertEqual(mock_py.call_count, 1)
        self.assertEqual(fig.get('data')[0], mock_py.call_args[0][0].get('data')[0]) 
Example #4
Source File: f_dispatch_curve_cooling_plant.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        # main data about technologies
        data = self.process_individual_dispatch_curve_cooling()
        graph = []
        analysis_fields = self.remove_unused_fields(data, self.analysis_fields)
        for field in analysis_fields:
            y = (data[field].values) / 1E6  # into MW
            trace = go.Bar(x=data.index, y=y, name=NAMING[field],
                           marker=dict(color=COLOR[field]))
            graph.append(trace)

        # data about demand
        for field in self.analysis_field_demand:
            y = (data[field].values) / 1E6  # into MW
            trace = go.Scattergl(x=data.index, y=y, name=NAMING[field],
                                 line=dict(width=1, color=COLOR[field]))

            graph.append(trace)

        return graph 
Example #5
Source File: e_dispatch_curve_heating_plant.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        # main data about technologies
        data = self.process_individual_dispatch_curve_heating()
        graph = []
        analysis_fields = self.remove_unused_fields(data, self.analysis_fields)
        for field in analysis_fields:
            y = (data[field].values) / 1E6  # into MW
            trace = go.Bar(x=data.index, y=y, name=NAMING[field],
                           marker=dict(color=COLOR[field]))
            graph.append(trace)

        # data about demand
        for field in self.analysis_field_demand:
            y = (data[field].values) / 1E6  # into MW
            trace = go.Scattergl(x=data.index, y=y, name=NAMING[field],
                               line=dict(width=1, color=COLOR[field]))

            graph.append(trace)

        return graph 
Example #6
Source File: c_requirements_curve_electricity.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        # main data about technologies
        data = self.process_individual_requirements_curve_electricity()
        graph = []
        analysis_fields = self.remove_unused_fields(data, self.analysis_fields)
        for field in analysis_fields:
            y = (data[field].values) / 1E6  # into MWh
            trace = go.Bar(x=data.index, y=y, name=NAMING[field],
                           marker=dict(color=COLOR[field]))
            graph.append(trace)

        # data about demand
        for field in self.analysis_field_demand:
            y = (data[field].values) / 1E6  # into MWh
            trace = go.Scattergl(x=data.index, y=y, name=NAMING[field],
                               line=dict(width=1, color=COLOR[field]))

            graph.append(trace)

        return graph 
Example #7
Source File: peak_load_supply.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        analysis_fields = self.remove_unused_fields(self.data, self.analysis_fields)
        if len(self.buildings) == 1:
            assert len(self.data) == 1, 'Expected DataFrame with only one row'
            building_data = self.data.iloc[0]
            traces = []
            area = building_data["GFA_m2"]
            x = ["Absolute [kW]", "Relative [kW/m2]"]
            for field in analysis_fields:
                name = NAMING[field]
                y = [building_data[field], building_data[field] / area * 1000]
                trace = go.Bar(x=x, y=y, name=name, marker=dict(color=COLOR[field]))
                traces.append(trace)
            return traces
        else:
            traces = []
            dataframe = self.data
            for field in analysis_fields:
                y = dataframe[field]
                name = NAMING[field]
                trace = go.Bar(x=dataframe["Name"], y=y, name=name, marker=dict(color=COLOR[field]))
                traces.append(trace)
            return traces 
Example #8
Source File: load_curve.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        data = self.calculate_hourly_loads()
        traces = []
        analysis_fields = self.remove_unused_fields(data, self.analysis_fields)
        for field in analysis_fields:
            y = data[field].values / 1E3  # to MW
            name = NAMING[field]
            trace = go.Bar(x=data.index, y=y, name=name, marker=dict(color=COLOR[field]))
            traces.append(trace)

        data_T = self.calculate_external_temperature()
        for field in ["T_ext_C"]:
            y = data_T[field].values
            name = NAMING[field]
            trace = go.Scattergl(x=data_T.index, y=y, name=name, yaxis='y2', opacity=0.2)
            traces.append(trace)
        return traces 
Example #9
Source File: peak_load.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        analysis_fields = self.remove_unused_fields(self.data, self.analysis_fields)
        if len(self.buildings) == 1:
            assert len(self.data) == 1, 'Expected DataFrame with only one row'
            building_data = self.data.iloc[0]
            traces = []
            area = building_data["GFA_m2"]
            x = ["Absolute [kW]", "Relative [W/m2]"]
            for field in analysis_fields:
                name = NAMING[field]
                y = [building_data[field], building_data[field] / area * 1000]
                trace = go.Bar(x=x, y=y, name=name, marker=dict(color=COLOR[field]))
                traces.append(trace)
            return traces
        else:
            traces = []
            dataframe = self.data
            for field in analysis_fields:
                y = dataframe[field]
                name = NAMING[field]
                trace = go.Bar(x=dataframe["Name"], y=y, name=name, marker=dict(color=COLOR[field]))
                traces.append(trace)
            return traces 
Example #10
Source File: peak_load.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def peak_load_building(data_frame, analysis_fields, title, output_path):
    # CREATE FIRST PAGE WITH TIMESERIES
    traces = []
    area = data_frame["GFA_m2"]
    data_frame = data_frame[analysis_fields]
    x = ["Absolute [kW] ", "Relative [W/m2]"]
    for field in analysis_fields:
        y = [data_frame[field], data_frame[field] / area * 1000]
        name = NAMING[field]
        trace = go.Bar(x=x, y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(images=LOGO, title=title, barmode='group', yaxis=dict(title='Peak Load'), showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #11
Source File: peak_load.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def peak_load_district(data_frame_totals, analysis_fields, title, output_path):
    traces = []
    data_frame_totals['total'] = data_frame_totals[analysis_fields].sum(axis=1)
    data_frame_totals = data_frame_totals.sort_values(by='total',
                                                      ascending=False)  # this will get the maximum value to the left
    for field in analysis_fields:
        y = data_frame_totals[field]
        total_perc = (y / data_frame_totals['total'] * 100).round(2).values
        total_perc_txt = ["(" + str(x) + " %)" for x in total_perc]
        name = NAMING[field]
        trace = go.Bar(x=data_frame_totals["Name"], y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(title=title, barmode='group', yaxis=dict(title='Peak Load [kW]'), showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #12
Source File: energy_end_use_intensity.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def energy_use_intensity_district(data_frame, analysis_fields, title, output_path):
    traces = []
    data_frame_copy = data_frame.copy()  # make a copy to avoid passing new data of the dataframe around the class
    for field in analysis_fields:
        data_frame_copy[field] = data_frame_copy[field] * 1000 / data_frame_copy["GFA_m2"]  # in kWh/m2y
        data_frame_copy['total'] = data_frame_copy[analysis_fields].sum(axis=1)
        data_frame_copy = data_frame_copy.sort_values(by='total',
                                                      ascending=False)  # this will get the maximum value to the left
    x = data_frame_copy["Name"].tolist()
    for field in analysis_fields:
        y = data_frame_copy[field]
        name = NAMING[field]
        trace = go.Bar(x=x, y=y, name=name, marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(images=LOGO, title=title, barmode='stack', yaxis=dict(title='Energy Use Intensity [kWh/m2.yr]'),
                       showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #13
Source File: visuals.py    From python-esppy with Apache License 2.0 6 votes vote down vote up
def createContent(self):
        values = self.getValues("y")
        colors = self._visuals._colors.getFirst(len(values))
        opacity = self.getOpt("opacity")

        self._data = []

        orientation = self.getOpt("orientation","vertical")

        if orientation == "horizontal":
            for i,v in enumerate(values):
                self._data.append(go.Bar(x=[0],y=[""],name=v,orientation="h",marker_color=colors[i]))

        else:
            for i,v in enumerate(values):
                self._data.append(go.Bar(x=[""],y=[0],name=v,opacity=opacity,marker_color=colors[i])) 
Example #14
Source File: peak_load_supply.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def peak_load_building(data_frame, analysis_fields, title, output_path):
    # CREATE FIRST PAGE WITH TIMESERIES
    traces = []
    area = data_frame["GFA_m2"]
    data_frame = data_frame[analysis_fields]
    x = ["Absolute [kW] ", "Relative [W/m2]"]
    for field in analysis_fields:
        y = [data_frame[field], data_frame[field] / area * 1000]
        name = NAMING[field]
        trace = go.Bar(x=x, y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(images=LOGO, title=title, barmode='group', yaxis=dict(title='Peak Load'), showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #15
Source File: peak_load_supply.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def peak_load_district(data_frame_totals, analysis_fields, title, output_path):
    traces = []
    data_frame_totals['total'] = data_frame_totals[analysis_fields].sum(axis=1)
    data_frame_totals = data_frame_totals.sort_values(by='total',
                                                      ascending=False)  # this will get the maximum value to the left
    for field in analysis_fields:
        y = data_frame_totals[field]
        total_perc = (y / data_frame_totals['total'] * 100).round(2).values
        total_perc_txt = ["(" + str(x) + " %)" for x in total_perc]
        name = NAMING[field]
        trace = go.Bar(x=data_frame_totals["Name"], y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(title=title, barmode='group', yaxis=dict(title='Peak Load [kW]'), showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #16
Source File: energy_end_use.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        graph = []
        analysis_fields = self.remove_unused_fields(self.data, self.analysis_fields)
        dataframe = self.data
        dataframe['total'] = dataframe[analysis_fields].sum(axis=1)
        dataframe.sort_values(by='total', ascending=False, inplace=True)
        dataframe.reset_index(inplace=True, drop=True)
        for field in analysis_fields:
            y = dataframe[field]
            name = NAMING[field]
            total_percent = (y / dataframe['total'] * 100).round(2).values
            total_percent_txt = ["(%.2f %%)" % x for x in total_percent]
            trace = go.Bar(x=dataframe["Name"], y=y, name=name, text=total_percent_txt, orientation='v',
                           marker=dict(color=COLOR[field]))
            graph.append(trace)

        return graph 
Example #17
Source File: energy_balance.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(analysis_fields, data_frame):
    """
    draws building heat balance graph

    :param analysis_fields:
    :param data_frame:
    :return:
    """

    graph = []
    for field in analysis_fields:
        y = data_frame[field]
        trace = go.Bar(x=data_frame.index, y=y, name=field.split('_kWh', 1)[0],
                       marker=dict(color=COLOR[field]))  # , text = total_perc_txt)
        graph.append(trace)

    return graph 
Example #18
Source File: plot_plotly.py    From vslam_evaluation with MIT License 6 votes vote down vote up
def running_times():
    rospack = rospkg.RosPack()
    data_path = os.path.join(rospack.get_path('vslam_evaluation'), 'out')
    df = pd.read_csv(os.path.join(data_path, 'runtimes.txt'),
        header=None,
        index_col=0)

    bars = []

    for col_idx in df:
        this_stack = df[col_idx].dropna()
        bars.append(
            go.Bar(
                x=this_stack.index,
                y=this_stack.values,
                name='Thread {}'.format(col_idx)))

    layout = go.Layout(
        barmode='stack',
        yaxis={'title': 'Running time [s]'})

    fig = go.Figure(data=bars, layout=layout)

    url = py.plot(fig, filename='vslam_eval_run_times') 
Example #19
Source File: energy_end_use_intensity.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def energy_use_intensity(data_frame, analysis_fields, title, output_path):
    # CREATE FIRST PAGE WITH TIMESERIES
    traces = []
    area = data_frame["GFA_m2"]
    x = ["Absolute [MWh/yr]", "Relative [kWh/m2.yr]"]
    for field in analysis_fields:
        name = NAMING[field]
        y = [data_frame[field], data_frame[field] / area * 1000]
        trace = go.Bar(x=x, y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(images=LOGO, title=title, barmode='stack', showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #20
Source File: HomeDetailsComponent.py    From anvil-course with MIT License 6 votes vote down vote up
def load_data(self):
    measurements = data_access.my_measurements()
    if not measurements:
      return
    
    x = []
    h = []
    w = []
    for idx, m in enumerate(measurements):
      x.append(idx + 1)
      h.append(m['RestingHeartRate'])
      w.append(m['WeightInPounds'])
      
    self.plot_weight_history.data = [
      go.Scatter(
      x = x,
      y = h,
      name='Heart rate'),
      go.Bar(
        x = x,
        y = w,
        name="Weight (lbs)"
      )
    ] 
Example #21
Source File: c_annual_costs.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def calc_graph(self):
        data = self.process_generation_total_performance_pareto()
        data = self.normalize_data(data, self.normalization, self.analysis_fields)
        self.data_clean = data
        graph = []
        for field in self.analysis_fields:
            y = data[field].values
            flag_for_unused_technologies = all(v == 0 for v in y)
            if not flag_for_unused_technologies:
                trace = go.Bar(x=data['individual_name'], y=y, name=NAMING[field],
                               marker=dict(color=COLOR[field]))
                graph.append(trace)

        return graph 
Example #22
Source File: bar_plot.py    From DataPlotly with GNU General Public License v2.0 5 votes vote down vote up
def name():
        return PlotType.tr('Bar Plot') 
Example #23
Source File: c_solar_collector_ET_potential.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def calc_graph(self):
        data = self.SC_ET_hourly_aggregated_kW()
        traces = []
        analysis_fields = self.remove_unused_fields(data, self.sc_et_analysis_fields)
        for field in analysis_fields:
            if self.normalization != "none":
                y = data[field].values  # in kW
            else:
                y = data[field].values / 1E3  # to MW

            name = NAMING[field]
            trace = go.Bar(x=data.index, y=y, name=name, marker=dict(color=COLOR[field]), showlegend=True)
            traces.append(trace)
        return traces 
Example #24
Source File: energy_use_intensity.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def calc_graph(self):
        analysis_fields = self.remove_unused_fields(self.data, self.analysis_fields)
        if len(self.buildings) == 1:
            assert len(self.data) == 1, 'Expected DataFrame with only one row'
            building_data = self.data.iloc[0]
            traces = []
            area = building_data["GFA_m2"]
            x = ["Absolute [MWh/yr]", "Relative [kWh/m2.yr]"]
            for field in analysis_fields:
                name = NAMING[field]
                y = [building_data[field], building_data[field] / area * 1000]
                trace = go.Bar(x=x, y=y, name=name, marker=dict(color=COLOR[field]))
                traces.append(trace)
            return traces
        else:
            traces = []
            dataframe = self.data
            for field in analysis_fields:
                dataframe[field] = dataframe[field] * 1000 / dataframe["GFA_m2"]  # in kWh/m2y
            dataframe['total'] = dataframe[analysis_fields].sum(axis=1)
            dataframe.sort_values(by='total', ascending=False, inplace=True)
            dataframe.reset_index(inplace=True, drop=True)
            for field in analysis_fields:
                y = dataframe[field]
                name = NAMING[field]
                trace = go.Bar(x=dataframe["Name"], y=y, name=name, marker=dict(color=COLOR[field]))
                traces.append(trace)
            return traces 
Example #25
Source File: a_photovoltaic_potential.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def calc_graph(self):
        data = self.PV_hourly_aggregated_kW()
        traces = []
        analysis_fields = self.remove_unused_fields(data, self.pv_analysis_fields)
        for field in analysis_fields:
            if self.normalization != "none":
                y = data[field].values  # in kW
            else:
                y = data[field].values / 1E3  # to MW

            name = NAMING[field]
            trace = go.Bar(x=data.index, y=y, name=name, marker=dict(color=COLOR[field]))
            traces.append(trace)
        return traces 
Example #26
Source File: a_solar_radiation.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def calc_graph(self):
        data = self.solar_hourly_aggregated_kW()
        traces = []
        analysis_fields = self.remove_unused_fields(data, self.solar_analysis_fields)
        for field in analysis_fields:
            if self.normalization != "none":
                y = data[field].values  # in kW
            else:
                y = data[field].values / 1E3  # to MW

            name = NAMING[field]
            trace = go.Bar(x=data.index, y=y, name=name, marker=dict(color=COLOR[field]))
            traces.append(trace)
        return traces 
Example #27
Source File: components.py    From webmc3 with Apache License 2.0 5 votes vote down vote up
def autocorr_figure(trace_info, varname, ix_slice=None):
    max_lag = min(100, len(trace_info))

    if ix_slice is not None:
        max_lag = min(max_lag, ix_slice.stop - ix_slice.start)

    x = np.arange(max_lag)

    return {
        'data': [
            go.Bar(
                x=x + chain_ix / trace_info.nchains,
                y=chain_autocorr,
                name="Chain {}".format(chain_ix),
                marker={'line': {'width': 1. / trace_info.nchains}}
            )
            for chain_ix, chain_autocorr in enumerate(
                trace_info.autocorr(varname, ix_slice=ix_slice)
            )
        ],
        'layout': go.Layout(
            xaxis={'title': "Lag"},
            yaxis={'title': "Sample autocorrelation"},
            showlegend=False
        )
    } 
Example #28
Source File: advanced_demo.py    From dash-ui with MIT License 5 votes vote down vote up
def create_total_exports_bar(state):
    my_df = df.sort_values('total exports', ascending=False)
    trace = go.Bar(
        x=my_df['state'],
        y=my_df['total exports'],
        marker=dict(
            color=['red' if x == state else 'grey' for x in my_df['state']]
        ))
    return go.Figure(data=[trace], layout={
        'showlegend': False,
        'autosize': True,
        'title':
        "{:s}'s agriculture exports vs. other states".format(state)
    }) 
Example #29
Source File: advanced_demo.py    From dash-ui with MIT License 5 votes vote down vote up
def create_all_bar(state):
    vs = list(set(df.columns) - {"Unnamed: 0", "total exports", "state"})
    row = df[df["state"] == state].iloc[0]
    trace = go.Bar(
        x=vs,
        y=[row[v] for v in vs])
    return go.Figure(data=[trace], layout={
        'showlegend': False,
        'title':
        "{:s}'s agriculture distribution".format(state)
    }) 
Example #30
Source File: b_photovoltaic_thermal_potential.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def calc_graph(E_analysis_fields_used, Q_analysis_fields_used, data_frame):
    # calculate graph
    graph = []
    monthly_df = (data_frame.set_index("DATE").resample("M").sum() / 1000).round(2)  # to MW
    monthly_df["month"] = monthly_df.index.strftime("%B")
    E_total = monthly_df[E_analysis_fields_used].sum(axis=1)
    Q_total = monthly_df[Q_analysis_fields_used].sum(axis=1)

    for field in Q_analysis_fields_used:
        y = monthly_df[field]
        total_perc = (y.divide(Q_total) * 100).round(2).values
        total_perc_txt = ["(" + str(x) + " %)" for x in total_perc]
        trace1 = go.Bar(x=monthly_df["month"], y=y, yaxis='y2', name=field.split('_kWh', 1)[0], text=total_perc_txt,
                        marker=dict(color=COLOR[field], line=dict(color="rgb(105,105,105)", width=1)),
                        opacity=1, width=0.3, offset=0, legendgroup=field.split('_Q_kWh', 1)[0])
        graph.append(trace1)

    for field in E_analysis_fields_used:
        y = monthly_df[field]
        total_perc = (y / E_total * 100).round(2).values
        total_perc_txt = ["(" + str(x) + " %)" for x in total_perc]
        trace2 = go.Bar(x=monthly_df["month"], y=y, name=field.split('_kWh', 1)[0], text=total_perc_txt,
                        marker=dict(color=COLOR[field]), width=0.3, offset=-0.35,
                        legendgroup=field.split('_E_kWh', 1)[0])
        graph.append(trace2)

    return graph