Beispiel #1
0
 def figure(self) -> go.Figure:
     return (go.Figure(
         go.Waterfall(
             orientation="v",
             measure=self.MEASURES,
             x=self.ORDER,
             textposition="outside",
             text=self.create_bartext(),
             y=[self.qc_vols[key] for key in self.ORDER],
             connector={"mode": "spanning"},
         )).update_layout(
             plot_bgcolor="white",
             title="Waterfall chart showing changes from SWATINIT to SWAT",
             margin={
                 "t": 50,
                 "b": 50,
                 "l": 50,
                 "r": 50
             },
         ).update_yaxes(title="Water Volume (Mrm3)",
                        range=self.range,
                        **axis_defaults()).update_xaxes(
                            type="category",
                            tickangle=-45,
                            tickfont_size=17,
                            **axis_defaults(showgrid=False),
                        ))
Beispiel #2
0
    def _plot_force_df_coef(self, force_df, name=None):
        """
        Plot forced with coef column (useful in regressions)
        """
        height = max(600, int(len(force_df) / 3 * 100))

        measure = ["relative"] * len(force_df)
        x, text, y = [], [], []
        for i, row in force_df.iterrows():
            y.append(row['feature'][:100])
            text.append(f"{row['overall']} ({row['diff_perc']:+.2f}%)")
            x.append(row['diff_perc'])

        fig = go.Figure(go.Waterfall(
            name="20", orientation="h",
            measure=["relative"] * len(force_df),
            x=x,
            textposition="outside",
            text=text,
            y=y,
            connector={"line": {"color": "rgb(63, 63, 63)"}},
        ))

        title = "Analysis " if isNone(name) else f"Analysis of {name}"
        fig.update_layout(
            title=title,
            showlegend=False,
            height=height,
        )
        fig.update_yaxes(showticklabels=False)
        fig.update_xaxes(showticklabels=False)

        return fig
Beispiel #3
0
def update_graph(options_chosen):

    dff = df[df['Source'].isin(options_chosen)]
    print(dff['Source'].unique())

    fig = go.Figure(
        go.Waterfall(
            name="20",
            orientation="v",
            measure=dff['Measure'],
            x=dff['Source'],
            textposition="inside",
            text=dff['Contribution'],
            y=dff['Contribution'],
            increasing={"marker": {
                "color": "#8F2738"
            }},
            decreasing={"marker": {
                "color": "Teal"
            }},
            totals={
                "marker": {
                    "color": "#ffb01f",
                    "line": {
                        "color": "gold",
                        "width": 3
                    }
                }
            },
            connector={"line": {
                "color": "#C0C0C0"
            }},
        ))
    fig.update_yaxes(visible=True, title_text='W/m<sup>2</sup>')
    return (fig)
Beispiel #4
0
    def _plot_force_df_perc(self, force_df, name=None):
        """
        Plot forced with perc column (useful in biclassifications)
        """
        learn = self.learn
        height = max(600, int(len(force_df) / 3 * 100))
        x, text, y = [], [], []
        for i, row in force_df.iterrows():
            y.append(row['feature'][:100])
            text.append(f"{row['overall']:.5f} ({row['diff_perc']:+.2f}%)")
            x.append(row['overall_diff'])

        fig = go.Figure(go.Waterfall(
            name="20", orientation="h",
            measure=["relative"] * len(force_df),
            x=x,
            textposition="outside",
            text=text,
            y=y,
            connector={"line": {"color": "rgb(63, 63, 63)"}},
        ))

        clss = learn.dls.vocab[0]
        title = "" if isNone(name) else f"Analysis of {name}"
        title = f"{title}\n Probability of item is '{clss}'"
        fig.update_layout(
            title=title,
            showlegend=False,
            height=height,
        )
        fig.update_yaxes(showticklabels=False)

        return fig
Beispiel #5
0
def waterfall(df_in, date, interval):
    
    x_list, y_list, y_range = calculations.waterfall_data_prep(df_in, date)
    
    fig_waterfall = go.Figure()
    
    fig_waterfall.add_trace(go.Waterfall(
    name = 'networth', orientation = "v",
    measure = ["absolute", "relative", "relative", "relative", "relative", "relative", "relative", "relative", "total"],
    x = x_list,
    textposition = "outside",
    #text = ["", "+80", "", "-40", "-20", "Total"],
    y = y_list,
    connector = {"line":{"color":"rgb(63, 63, 63)"}},))
    
    #fig_waterfall.update_xaxes(showgrid=False, showline=True, linewidth=2, linecolor='#404b6b', mirror=True, tickfont=dict(family='sans-serif',color='#fffef9',size=14))
    fig_waterfall.update_yaxes(showgrid=True, showline=False, zeroline=False, gridcolor='#d5d7d8',
                               tickfont=dict(family='sans-serif',color='black',size=14),
                               range=y_range)
    
    
    fig_waterfall.update_layout(margin={'l':40,'b':0,'r':0,'t':20,}, yaxis={'type':'linear'},plot_bgcolor='white',paper_bgcolor='white',
                                height=260,width=580, hoverlabel=dict(
                                                                    bgcolor="white",
                                                                    font_size=16,
                                                                    font_family="Rockwell"
                                                                ))
    
    return fig_waterfall
Beispiel #6
0
def closed_income_composition_graph_html(portfolio_rows, base_currency):
    profits = {}
    courses = _get_current_currency_courses(base_currency)
    for row in portfolio_rows:
        profit = row.income
        profits[row.ticker] = round(
            profit *
            _get_current_currency_course(courses, base_currency, row.currency),
            1)
    profits = dict(
        sorted(profits.items(), key=lambda item: item[1], reverse=True))

    fig = go.Figure(
        go.Waterfall(
            orientation="v",
            measure=["relative"
                     for i in range(len(list(profits.keys())))] + ['total'],
            x=list(profits.keys()) + ['total'],
            textposition="outside",
            textangle=-90,
            texttemplate='%{text:.2s}',
            text=list(profits.values()) + [sum(list(profits.values()))],
            y=list(profits.values()) + [sum(list(profits.values()))],
        ))

    fig.update_layout(title="Состав дохода (закрытые позиции)",
                      showlegend=False)
    return fig.to_html(full_html=False, include_plotlyjs=False)
def waterfall_plot(cashflow, label=""):
    n = cashflow.shape[0]
    fig = go.Figure(
        go.Waterfall(name="",
                     orientation="v",
                     measure=["absolute"] * n,
                     x=["Mês " + str(x) for x in range(n)],
                     textposition="outside",
                     y=cashflow,
                     connector={"line": {
                         "width": 0,
                         "color": "black"
                     }},
                     totals={
                         "marker": {
                             "color": "#ff774a",
                             "line": {
                                 "color": "black",
                                 "width": 1
                             }
                         }
                     }))
    fig.update_layout(
        title={
            "text": label,
            "x": 0.5,
            "xanchor": "center"
        },
        showlegend=False,
    )
    fig.show()
Beispiel #8
0
def waterfall(df_in, date):
    
    x_list, y_list, y_range = calculations.waterfall_data_prep(df_in, date)
    
    fig_waterfall = go.Figure()
    
    fig_waterfall.add_trace(go.Waterfall(
    name = 'networth', orientation = "v",
    measure = ["absolute", "relative", "relative", "relative", "relative", "relative", "relative", "relative", "total"],
    x = x_list,
    textposition = "outside",
    y = y_list,
    connector = {"line":{"color":"rgb(63, 63, 63)"}},))
    
    fig_waterfall.update_xaxes(autorange=True, showline=True, title="")
    fig_waterfall.update_yaxes(autorange=False, range=y_range,
                            gridcolor="rgba(127, 127, 127, 0.2)",
                            mirror=False,
                            nticks=4,
                            showgrid=True,
                            showline=True,
                            linewidth=1,
                            ticklen=5,
                            ticks='outside',
                            #title="",
                            type="linear",
                            zeroline=False,
                            zerolinewidth=4,)
    
    
    fig_waterfall.update_layout(margin={'l':10,'b':10,'r':0,'t':20,}, yaxis={'type':'linear'},plot_bgcolor='white',paper_bgcolor='white',
                                height=200,width=330, autosize=False,hovermode='closest')
    
    return fig_waterfall
Beispiel #9
0
def plot_waterfall(measures,
                   dropdown_tag,
                   x_labels,
                   y_values,
                   disp_values,
                   dicts_ar,
                   title=None):
    """
    Function to display waterfall plots with a dropdown selector in plotly.

    Different data slices can be selected by timestamp from a dropdown selection menu.
    These slices of data are contained within dictionary objects passes as a list to fig.update_layout.
    Code assumes that dropdown information shouldn't be plotted.

    Args:
        measures (list): Defines the type of column to plot in the waterfall - 'absolute' or 'relative'.
        dropdown_tag (str): The column that contains the timestamp values.
        x_labels (list): Defines the names for the columns to plot.
        y_labels (list): Initial data to plot.
        disp_values (numpy.ndarray) Initial data to display.
        dicts_ar (list): List of dicts containing data to be passed to fig.update_layout.
        title (str): Plot title to be displayed.

    Returns:
        None
    """
    # Define the initial plot
    fig = go.Figure(
        go.Waterfall(
            orientation="v",
            measure=measures,
            x=x_labels,
            textposition="outside",
            y=y_values,
            text=disp_values,
            connector={"line": {
                "color": "rgb(63, 63, 63)"
            }},
        ))

    # Add dynamic plot that is built from the dicts inside dicts_ar
    fig.update_layout(updatemenus=[
        dict(buttons=dicts_ar,
             direction="down",
             pad={
                 "r": 10,
                 "t": 10
             },
             showactive=True,
             xanchor="auto",
             x=0.25,
             yanchor="top",
             y=1.2),
    ])

    fig.update_layout(title=title, showlegend=False)

    fig.show()
Beispiel #10
0
def getwaterfall(batch=2017, base=3000):
    frame = grouped[grouped.year == batch].copy()
    first = str(batch)
    first = first[2:]
    second = str(int(first) + 1)
    title_ = 'O Level Batch of ' + str(batch) + '-' + second
    nine = int(frame['Number of Students in 9-C'])

    ten = grouped[grouped.year == batch + 1]
    dropouts_in_10c = nine - int(ten['Students retained in 10-C'])
    new_students_in_10c = int(ten['New Students in 10-C'])
    total_in_10c = int(ten['Number of Students in 10-C'])

    eleven = grouped[grouped.year == batch + 2]
    dropouts_in_11c = total_in_10c - int(eleven['Students retained in 11-C'])
    new_students_in_11c = int(eleven['New students in 11-C'])
    total_in_11c = int(eleven['Number of Students in 11-C'])

    numbers = [
        nine - base, dropouts_in_10c * -1, new_students_in_10c, None,
        dropouts_in_11c * -1, new_students_in_11c, None
    ]
    texts = [
        nine, dropouts_in_10c, new_students_in_10c, total_in_10c,
        dropouts_in_11c, new_students_in_11c, total_in_11c
    ]
    texts = [str(i) for i in texts]
    fig = go.Figure(
        go.Waterfall(
            x=[["9-C", "10-C", "10-C", "10-C", "11-C", "11-C", "11-C"],
               [
                   "Enrolled in 9-C", "Dropouts", "New", "total", "Dropouts",
                   "New", "total"
               ]],
            measure=[
                "absolute", "relative", "relative", "total", "relative",
                "relative", "total"
            ],
            y=numbers,
            base=base,
            text=texts,
            textposition="auto",
            decreasing={"marker": {
                "color": "#DC143C"
            }},
            increasing={"marker": {
                "color": "#50C878"
            }},
            totals={"marker": {
                "color": "deep sky blue"
            }}))

    fig.update_layout(title=title_,
                      waterfallgap=0.5,
                      width=1000,
                      paper_bgcolor="white")
    fig.update_yaxes(title_text='Number of Students')
    fig.show()
Beispiel #11
0
def waterfall_plot_transactions(transactions: Transactions, plot_dates=True):
	fig = go.Figure()
	fig.add_trace(
		go.Waterfall(
			x = [t.date for t in transactions] if plot_dates else None,
			y = [t.ammount for t in transactions],
			text = [str(t.date) + '<br>Comment: ' + t.comment + '<br>Tags: ' + str(t.tags) for t in transactions],
			offset = 0, # See https://plot.ly/python/reference/#waterfall-offset
		)
	)
	return fig
    def is_waterfall_plot(df, index_no):
        measure_list = np.array(["relative", "relative", "total", "relative","total","relative",'relative',"total",'relative',"total"])

        if len(index_no) > 0:
            measure_list = measure_list[np.arange(len(measure_list)) != index_no]
        fig = go.Figure()
        fig.add_trace(go.Waterfall(
        orientation='v',
        measure = measure_list,
        x = np.array(df['index']),
        y = df.Amount))

        return st.plotly_chart(fig) #fig.show()
Beispiel #13
0
def simple_waterfall_chart(x_list, y_list):
    fig = go.Figure(go.Waterfall(
        name="20", orientation="v",
        measure=["relative"] * (len(x_list) - 1) + ["total"],
        x=x_list,
        textposition="outside",
        y=y_list,
        connector={"line": {"color": "rgb(63, 63, 63)"}},
    ))

    fig.update_layout(
        showlegend=False
    )
    fig.update_layout(margin=dict(l=0, r=0, t=0, b=0), )
    return fig
def drawWaterfall(total_list, path):
    
    fig = go.Figure()
    fig.add_trace(go.Waterfall(
        x = list(range(len(total_list))),
        orientation = "h",
        measure=['absolute'] + ['relative' for i in range(len(total_list) - 1)],
        base=0,
        decreasing = {"marker":{"color":"Maroon", "line":{"color":"red", "width":2}}},
        increasing = {"marker":{"color":"Teal"}},
    ))

    fig.update_layout(title="Waterfall", waterfallgap=0.3)

    # fig.show()

    fig.write_image(path + "_waterfall.png")
Beispiel #15
0
def attribution_waterfall_chart(factor_selection,to_plot):
    n = len(factor_selection)
    str1 = to_plot
    import plotly.graph_objects as go
    df4=make_dataset(factor_selection)
    fig = go.Figure(go.Waterfall(
    name = "Absolute " + str1 + " Attribution", orientation = "h", measure = ["relative"]*(n+1) +  ["total"],
    y = factor_selection + ["Alpha","Total Returns"],
    x = list(df4[str1]),
    connector = {"mode":"between", "line":{"width":4, "color":"rgb(0, 0, 0)", "dash":"solid"}}
    ))
    fig.update_layout(title={'text': "Absolute " + str1 + " Attribution", 'y':0.97, 'x':0.5,'xanchor': 'center','yanchor': 'top'}, 
                      font=dict(size=18,),
                      margin = dict(t=60,r=0,b=0,pad=0),
                      height = 350, width = 700,
                      xaxis= {'showspikes': True, 'title': '%age returns'},
                      yaxis= {'showspikes': True},
                      spikedistance = 10)
    return fig
Beispiel #16
0
def _waterfall_df(df,
                  x,
                  y,
                  theme,
                  agg_func='sum',
                  orientation='v',
                  show_label=False):
    dff = df.groupby(x, as_index=True,
                     sort=False).agg({y: agg_func})[y].reset_index()
    initial = dff[y].iloc[0]
    value_sum = dff[y].sum()
    dff[y] = dff[y].diff(periods=1)
    dff[y].iloc[0] = initial
    dff = dff.append({x: 'Total', y: value_sum}, ignore_index=True)
    text = dff[y].astype(
        str).tolist()[:-1] + ['Total'] if show_label == True else None
    fig = go.Figure(
        go.Waterfall(
            orientation=orientation,
            measure=sum([['relative']
                         for _ in range(df[x].unique().shape[0])], []) +
            ['total'],
            x=dff[x],
            textposition="outside",
            text=text,
            y=dff[y],
            connector={"line": {
                "color": "rgb(63, 63, 63)"
            }}))

    fig.update_layout(title=None,
                      showlegend=False,
                      template=theme,
                      waterfallgap=0.3)
    fig.update_xaxes(showgrid=False)
    fig.update_yaxes(showgrid=False)
    return fig
 go.Waterfall(
     name="20",
     orientation="v",
     measure=[
         "relative", "relative", "total", "relative", "relative", "total",
         "relative", "total"
     ],
     x=[
         "Revenue", "Cost of Revenue", "Gross Profit", "R&D Expenses",
         "SG&A Expense", "Operating Expenses", "Interest Expense",
         "Earnings before Tax", "Income Tax Expense", "Net Income Com"
     ],
     textposition="outside",
     text=[
         REV / 1000, COGs / 1000, GrossProfit / 1000, RD / 1000, GA / 1000,
         OperExp / 1000, INT / 1000, EBT / 1000, IncTax / 1000,
         NetInc / 1000
     ],
     y=[REV, COGs, GrossProfit, RD, GA, OperExp, INT, EBT, IncTax, NetInc],
     connector={"line": {
         "color": "rgba(63, 63, 63, 0.7)"
     }},
     decreasing={"marker": {
         "color": "rgba(219, 64, 82, 0.7)"
     }},
     increasing={"marker": {
         "color": "rgba(50, 171, 96, 0.7)"
     }},
     totals={"marker": {
         "color": "rgba(55, 128, 192, 0.7)"
     }},
 ))
Beispiel #18
0
    def visualizations(self, data, base_year, end_year, loa, model,
                       energy_type, rename_dict):
        """Visualize additive LMDI results in a waterfall chart, opens in internet browsers and
        user must save manually (from plotly save button)
        """
        data = data[data['@filter|Model'] == model.capitalize()]

        structure_cols = []
        for column in data.columns:
            if column.endswith('Structure'):
                structure_cols.append(column)

        if len(structure_cols) == 1:
            data = data.rename(
                columns={structure_cols[0]: '@filter|Measure|Structure'})
        elif len(structure_cols) > 1:
            data['@filter|Measure|Structure'] = data[structure_cols].sum(
                axis=1)  # Current level total structure
            to_drop = [
                s for s in structure_cols if s != '@filter|Measure|Structure'
            ]
            data = data.drop(to_drop, axis=1)

        x_data = []

        if '@filter|Measure|Structure' in data.columns:
            x_data.append('@filter|Measure|Structure')
        else:
            for c in data.columns:
                if 'Structure' in c:
                    x_data.append(c)

        if "@filter|Measure|Intensity" in data.columns:
            x_data.append("@filter|Measure|Intensity")
        else:
            for c in data.columns:
                if 'Intensity' in c:
                    x_data.append(c)

        if "@filter|Measure|Activity" in data.columns:
            x_data.append("@filter|Measure|Activity")
        else:
            for c in data.columns:
                if c.endswith('Activity'):
                    x_data.append(c)

        loa = [l.replace("_", " ") for l in loa]
        if loa[0] == loa[-1]:
            loa = [loa[0]]
        else:
            loa = [loa[0], loa[-1]]

        final_year = max(data['@timeseries|Year'])

        data_base = data[data['@timeseries|Year'] == base_year][x_data]
        data_base['intial_energy'] = self.energy_data.loc[base_year,
                                                          self.total_label]

        data = data[data['@timeseries|Year'] == end_year][x_data]
        if self.end_year in self.energy_data.index:
            data['final_energy'] = self.energy_data.loc[end_year,
                                                        self.total_label]
        else:
            data['final_energy'] = self.energy_data.loc[
                max(self.energy_data.index), self.total_label]

        x_data = ['intial_energy'] + x_data + ['final_energy']
        y_data = pd.concat([data_base, data],
                           ignore_index=True,
                           axis=0,
                           sort=False).fillna(0)
        y_data = y_data[x_data]

        y_data.loc[:, 'final_energy'] = 0
        y_data = y_data.sum(axis=0).values.tolist()
        y_labels = [self.format_y_vals(y) for y in y_data]

        x_labels = [x_.replace('@filter|Measure|', '') for x_ in x_data]
        x_labels = [x.replace("_", " ").title() for x in x_labels]

        measure = ['relative'] * 4 + ['total']

        fig = go.Figure(
            go.Waterfall(name="Change",
                         orientation="v",
                         measure=measure,
                         x=x_labels,
                         textposition="outside",
                         y=y_data,
                         text=y_labels,
                         connector={"line": {
                             "color": "rgb(63, 63, 63)"
                         }}))

        title = f"Change in {energy_type.capitalize()} Energy Use (TBtu) {base_year}-{final_year} {' '.join([l.title() for l in loa])}"
        fig.update_layout(title=title, font=dict(size=18), showlegend=True)
        fig.show()
Beispiel #19
0
def main(stackname, profile='default', region='us-east-2'):
    session = boto3.session.Session(profile_name=profile, region_name=region)
    cloudformation_client = session.client('cloudformation')
    paginator = cloudformation_client.get_paginator('describe_stack_events')
    response = paginator.paginate(StackName=stackname)
    first = True
    start = None
    data = {}
    # Drop it, flip it, and reverse it.
    events = order_events([e for e in response])
    for page in events:
        for event in page['StackEvents']:
            if first:
                start = event['Timestamp']
                first = False
            # Initialize the waterfall for this Resource
            if event['LogicalResourceId'] not in data:
                base = event['Timestamp'] - start
                data[event['LogicalResourceId']] = {
                    'result': {
                        'x': [],
                        'y': [],
                        'text': [],
                        'textfont': {
                            "family": "Open Sans, light",
                            "color": "black"
                        },
                        'textposition': "outside",
                        'width': 0.5,
                        'base': base.seconds,
                        'measure': [],
                        'increasing': {
                            "marker": {
                                "color": "LightBlue"
                            }
                        }
                    },
                    'start_time': event['Timestamp']
                }
            # Calculate the distance from stack start
            duration = event['Timestamp'] - \
                data[event['LogicalResourceId']]['start_time']
            # If there are no values recorded for this resource ID, set the first
            # one as an absolute. TODO: this may need to change.
            if len(data[event['LogicalResourceId']]['result']['measure']) == 0:
                data[event['LogicalResourceId']]['result']['measure'].append(
                    'absolute')
            # Otherwise set it as relative
            else:
                data[event['LogicalResourceId']]['result']['measure'].append(
                    'relative')
            # Record the results
            data[event['LogicalResourceId']]['result']['x'].append(
                duration.seconds)
            data[event['LogicalResourceId']]['result']['y'].append(
                event['LogicalResourceId'])

            # If this is the last event then set a text label for the
            # total time the resource took to deploy.
            if event['ResourceStatus'] == 'CREATE_COMPLETE':
                resource_duration = sum(
                    data[event['LogicalResourceId']]['result']['x'])
                data[event['LogicalResourceId']]['result']['text'].append(
                    format_time_from_seconds(resource_duration))
            else:
                data[event['LogicalResourceId']]['result']['text'].append('')

    # Format the total run time for display
    total_time = format_time_from_seconds(data[stackname]["result"]["x"][-1])

    fig = go.Figure()
    fig.update_layout(title={
        'text':
        f'<span style="color:#000000">CloudFormation Waterfall - {stackname}<br /><b>Total Time: {total_time}</b></span>'
    },
                      showlegend=False,
                      height=(len(data) * 30),
                      font={
                          'family': 'Open Sans, light',
                          'color': 'black',
                          'size': 14
                      },
                      plot_bgcolor='#FFF')
    fig.update_xaxes(title="Time in Seconds",
                     tickangle=-45,
                     tickfont=dict(family='Open Sans, light',
                                   color='black',
                                   size=12))
    fig.update_yaxes(title="CloudFormation Resources",
                     tickangle=0,
                     tickfont=dict(family='Open Sans, light',
                                   color='black',
                                   size=12),
                     linecolor='#000')
    for k, v in data.items():
        fig.add_trace(go.Waterfall(orientation='h', **v['result']))
    fig.show()
 def test_pop_data(self):
     fig = go.Figure(data=go.Waterfall(y=[2, 1, 3]))
     self.assertEqual(fig.pop("data"), (go.Waterfall(y=[2, 1, 3]), ))
     self.assertEqual(fig.data, ())
    def test_scalar_trace_as_data(self):
        fig = go.Figure(data=go.Waterfall(y=[2, 1, 3]))
        self.assertEqual(fig.data, (go.Waterfall(y=[2, 1, 3]), ))

        fig = go.Figure(data=dict(type="waterfall", y=[2, 1, 3]))
        self.assertEqual(fig.data, (go.Waterfall(y=[2, 1, 3]), ))
Beispiel #22
0
print(p.value(x), p.value(y), p.value(z), p.value(a),
      p.value(hosp_prob.objective))

#-------------------------------VISUALISATION-----------------------------------

fig = go.Figure(
    go.Waterfall(
        name="20",
        orientation="v",
        measure=['relative', 'relative', 'relative', 'relative', 'total'],
        x=[
            'Medical Staff', 'Nursing Staff', 'Admin Staff', 'Cleaning Staff',
            'Total Cost'
        ],
        textposition="outside",
        text=[(p.value(x) * med_cost), (p.value(y) * nurs_cost),
              (p.value(z) * admin_cost), (p.value(a) * clean_cost),
              p.value(hosp_prob.objective)],
        y=[(p.value(x) * med_cost), (p.value(y) * nurs_cost),
           (p.value(z) * admin_cost), (p.value(a) * clean_cost),
           p.value(hosp_prob.objective)],
        connector={"line": {
            "color": "rgb(63, 63, 63)"
        }},
    ))

fig.update_layout(title="Optimised hospital staffing expenditure",
                  showlegend=False)

fig.show()
def update_graph3(option_slctd1, option_slctd2, option_slctd3):
    print('*' * 100)
    # Initial Filter
    df_bs = df_fin_filt_1.copy()
    df_bs = df_bs[df_bs["Sector"] == option_slctd1]
    df_bs = df_bs[df_bs["SGX_CoyName"] == option_slctd3]
    df_bs = df_bs[[option_slctd2, "Info_Label", "Statement_Type"]]
    df_bs[option_slctd2] = df_bs[option_slctd2]  #.abs()
    df_bs = df_bs[
        df_bs["Statement_Type"] ==
        'Cash_Flow']  # dff = dff[dff["Statement_Type"] == "Income_Statement"]]
    label_sort_ = [
        {
            'netIncome': 'absolute'
        },
        {
            'totalCashFromOperatingActivities': 'relative'
        },
        {
            'totalCashflowsFromInvestingActivities': 'relative'
        },
        {
            'totalCashFromFinancingActivities': 'relative'
        },
    ]
    df_corr = pd.DataFrame({
        'netIncome': [1],
        'totalCashFromOperatingActivities': [1],
        'totalCashflowsFromInvestingActivities': [1],
        'totalCashFromFinancingActivities': [1],
    })
    # ERROR req_labels = list(set().union(*(d.keys() for d in label_sort_)))
    req_labels = [i for s in [d.keys() for d in label_sort_] for i in s]
    req_measures = [i for s in [d.values() for d in label_sort_] for i in s]
    # Filter only required
    df_bs_filt = df_bs[df_bs["Info_Label"].isin(req_labels)]
    df_corr = df_corr[list(df_bs_filt["Info_Label"])].T.reset_index()
    df_corr.columns = ['Info_Label', 'Corrector']
    df_bs_filt_2 = pd.merge(df_bs_filt, df_corr, on=['Info_Label'])
    df_bs_filt_2 = convert_df_cols_to_float(df_bs_filt_2, [option_slctd2])
    # Order
    sorterIndex = dict(zip(req_labels, range(len(req_labels))))
    df_bs_filt_2['Order_id'] = df_bs_filt_2['Info_Label'].map(sorterIndex)
    df_bs_filt_2.sort_values(['Order_id'], inplace=True)
    req_vals_cor = [
        a * b for a, b in zip(list(df_bs_filt_2[option_slctd2]),
                              list(df_bs_filt_2['Corrector']))
    ]
    df_bs_filt_2[option_slctd2] = req_vals_cor
    # Set Chart X-values / Y-values
    x_labels = list(df_bs_filt_2['Info_Label'])  # req_labels
    y_labels = list(df_bs_filt_2[option_slctd2])
    # # adjust due to yahoo error
    # pos0 = 1
    # adjust0 = y_labels[x_labels.index("totalAssets")]-y_labels[x_labels.index("totalCurrentAssets")]
    # y_labels[pos0:pos0] = [adjust0]
    # x_labels[pos0:pos0] = ['totalNonCurrentAssets']
    # req_measures[pos0:pos0] = ['relative']
    # # y_labels[pos0:pos0] = [y_labels[x_labels.index("totalCurrentAssets")]]
    # pos1 = 3
    # adjust1 = y_labels[x_labels.index("totalLiab")]-y_labels[x_labels.index("totalCurrentLiabilities")]
    # y_labels[pos1:pos1] = [-adjust1]
    # x_labels[pos1:pos1] = ['totalNonCurrentLiabilities']
    # req_measures[pos1:pos1] = ['relative']
    # y_labels[4] = -y_labels[x_labels.index("totalCurrentLiabilities")]
    # #y_labels[pos1 + 2] = [-y_labels[x_labels.index("totalCurrentLiabilities")]]
    # # adjust due to yahoo error
    # pos2 = 6
    # adjust2 = y_labels[x_labels.index("totalStockholderEquity")] - y_labels[x_labels.index("commonStock")]
    # y_labels[pos2:pos2] = [adjust2]
    # x_labels[pos2:pos2] = ['retainedEarnings']
    # req_measures[pos2:pos2] = ['relative']
    # adjust due to yahoo error
    pos3 = len(y_labels)
    # adjust3 = y_labels[x_labels.index("netIncome")]+y_labels[x_labels.index("totalCashFromOperatingActivities")]
    adjust3 = sum(map(float, y_labels))
    y_labels[pos3:pos3] = [adjust3]
    x_labels[pos3:pos3] = ['Cash']
    req_measures[pos3:pos3] = ['total']

    # Graph
    import plotly.graph_objects as go
    fig = go.Figure(
        go.Waterfall(
            name="20",
            orientation="v",
            measure=req_measures,
            x=x_labels,
            textposition="outside",
            # text=["+60", "+80", "", "-40", "-20", "Total"],
            y=y_labels,
            connector={"line": {
                "color": "rgb(63, 63, 63)"
            }},
        ))
    title_ = 'Cash flow for {}'.format(option_slctd3)
    fig.update_layout(
        title=title_,
        # showlegend=True,
        width=700,
        height=500,
        xaxis_title="Content",
        yaxis_title="Value",
        template='plotly_dark')

    return fig
Beispiel #24
0
import plotly.express as px
import plotly.graph_objects as go

fig = go.Figure(
    go.Waterfall(name="20",
                 orientation="v",
                 measure=[
                     "relative", "relative", "relative", "relative",
                     "relative", "total"
                 ],
                 x=["Exp1", "Exp2", "Exp3", "Exp4", "Exp5", "Exp6"],
                 textposition="outside",
                 text=["100", "50", "130", "200", "40", "Total"],
                 y=[100, +50, 130, 200, 40, 0],
                 connector={"line": {
                     "color": "rgb(63, 63, 63)"
                 }},
                 increasing={"marker": {
                     "color": "green"
                 }},
                 totals={"marker": {
                     "color": "blue"
                 }}))

fig.update_layout(
    title="Waterfall Chart",
    showlegend=True,
    xaxis_title='X Axis Title',
    yaxis_title='Y Axis Title',
)
fig.layout.template = 'plotly_dark'
Beispiel #25
0
import plotly.graph_objects as go

fig = go.Figure(
    go.Waterfall(
        name="20",
        orientation="v",
        measure=[
            "relative", "relative", "total", "relative", "relative", "total"
        ],
        x=[
            "Sales", "Consulting", "Net revenue", "Purchases",
            "Other expenses", "Profit before tax"
        ],
        textposition="outside",
        text=["+60", "+80", "", "-40", "-20", "Total"],
        y=[60, 80, 0, -40, -20, 0],
        connector={"line": {
            "color": "rgb(63, 63, 63)"
        }},
    ))

fig.update_layout(title="Profit and loss statement 2018", showlegend=True)

fig.show()
Beispiel #26
0
 go.Waterfall(
     name="2018",
     orientation="h",
     measure=[
         "relative",
         "relative",
         "relative",
         "relative",
         "relative",
         "relative",
         "relative",
     ],
     y=[
         x[1] for x in [
             ["Выпуск", "Output (X)"],
             ["Импорт", "Import (IM)"],
             ["Статистическое расхождение", "Statistical discrepancy"],
             ["Экспорт", "Export (EX)"],
             ["Инвестиции", "Investment (I)"],
             ["Конечное потребление", "Final consumption (C)"],
             ["Промежуточное потребление", "Intermediate consumption (AX)"],
         ]
     ],
     x=[196.6, 21.6, -0.6, -31.9, -23.6, -69.3, -92.7],
     connector={
         "mode": "between",
         "line": {
             "width": 2,
             "color": "rgb(0, 0, 0)",
             "dash": "solid"
         },
     },
 ))
import pandas as pd

#df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df = pd.read_csv('./data/finance-charts-apple.csv')

# 1) Simple Waterfall Chart
fig = go.Figure(
    go.Waterfall(
        name="20",
        orientation="v",
        measure=[
            "relative", "relative", "total", "relative", "relative", "total"
        ],
        x=[
            "Продажи", "Консультации", "Чистый доход", "Покупки",
            "Прочие расходы", "Прибыль до вычета налога"
        ],
        textposition="outside",
        text=["+60", "+80", "", "-40", "-20", "Total"],
        y=[60, 80, 0, -40, -20, 0],
        connector={"line": {
            "color": "rgb(63, 63, 63)"
        }},
    ))

fig.update_layout(title="Отчет о прибылях и убытках 2018", showlegend=True)

fig.show()

# 2) Multi Category Waterfall Chart
fig = go.Figure()
def update_graph(option_slctd1, option_slctd2, option_slctd3):
    # Initial Filter
    df_is = df_fin_filt_1.copy()
    df_is = df_is[df_is["Sector"] == option_slctd1]
    df_is = df_is[df_is["SGX_CoyName"] == option_slctd3]
    df_is = df_is[[option_slctd2, "Info_Label", "Statement_Type"]]
    df_is[option_slctd2] = df_is[option_slctd2].abs()
    df_is = df_is[
        df_is["Statement_Type"] ==
        'Income_Statement']  # dff = dff[dff["Statement_Type"] == "Income_Statement"]
    # print('Incme Statement')
    # print(df_is)
    # Measure dictionary
    # label_sort_ = [
    #     {'totalRevenue': 'absolute'}, {'costOfRevenue': 'relative'},
    #     {'grossProfit': 'total'}, {'totalOperatingExpenses': 'relative'}, {'totalOtherIncomeExpenseNet': 'relative'},
    #     {'operatingIncome': 'total'},
    #     {'interestExpense': 'relative'}, {'researchDevelopment': 'relative'},
    #     {'incomeBeforeTax': 'total'}, {'incomeTaxExpense': 'relative'},
    #     {'netIncome': 'absolute'},
    # ]
    # df_corr = pd.DataFrame({
    #     'totalRevenue': [1], 'costOfRevenue': [-1],
    #     'grossProfit': [1], 'totalOperatingExpenses': [-1],'totalOtherIncomeExpenseNet': [-1],
    #     'operatingIncome': [1],
    #     'interestExpense': [-1], 'researchDevelopment': [-1],
    #     'incomeBeforeTax': [1], 'incomeTaxExpense': [-1],
    #     'netIncome': [1]
    # })
    # label_sort_ = [
    #     {'totalRevenue': 'absolute'}, {'costOfRevenue': 'relative'},
    #     {'grossProfit': 'total'},
    #     {'operatingIncome': 'total'},
    #     {'interestExpense': 'relative'}, {'researchDevelopment': 'relative'},
    #     {'incomeBeforeTax': 'total'}, {'incomeTaxExpense': 'relative'},
    #     {'netIncome': 'absolute'},
    # ]
    # df_corr = pd.DataFrame({
    #     'totalRevenue': [1], 'costOfRevenue': [-1],
    #     'grossProfit': [1],
    #     'operatingIncome': [1],
    #     'interestExpense': [-1], 'researchDevelopment': [-1],
    #     'incomeBeforeTax': [1], 'incomeTaxExpense': [-1],
    #     'netIncome': [1]
    # })
    label_sort_ = [{
        'totalRevenue': 'absolute'
    }, {
        'grossProfit': 'total'
    }, {
        'operatingIncome': 'total'
    }, {
        'incomeBeforeTax': 'total'
    }, {
        'netIncome': 'total'
    }]
    df_is_corr = pd.DataFrame({
        'totalRevenue': [1],
        'grossProfit': [1],
        'operatingIncome': [1],
        'incomeBeforeTax': [1],
        'netIncome': [1]
    })
    # ERROR req_labels = list(set().union(*(d.keys() for d in label_sort_)))
    req_labels = [i for s in [d.keys() for d in label_sort_] for i in s]
    req_measures = [i for s in [d.values() for d in label_sort_] for i in s]
    # req_correctors = [i for s in [d.values() for d in label_correction] for i in s]

    df_is_filt = df_is[df_is["Info_Label"].isin(req_labels)]

    df_is_corr = df_is_corr[list(df_is_filt["Info_Label"])].T.reset_index()
    df_is_corr.columns = ['Info_Label', 'Corrector']

    df_is_filt_2 = pd.merge(df_is_filt, df_is_corr, on=['Info_Label'])

    df_is_filt_2 = convert_df_cols_to_float(df_is_filt_2, [option_slctd2])

    sorterIndex = dict(zip(req_labels, range(len(req_labels))))
    df_is_filt_2['Order_id'] = df_is_filt_2['Info_Label'].map(sorterIndex)
    df_is_filt_2.sort_values(['Order_id'], inplace=True)

    req_vals_cor = [
        a * b for a, b in zip(list(df_is_filt_2[option_slctd2]),
                              list(df_is_filt_2['Corrector']))
    ]
    df_is_filt_2[option_slctd2] = req_vals_cor

    x_labels = list(df_is_filt_2['Info_Label'])  # req_labels
    y_labels = list(df_is_filt_2[option_slctd2])

    # adjust due to yahoo error
    pos0 = 1
    adjust0 = y_labels[x_labels.index("grossProfit")] - y_labels[
        x_labels.index("totalRevenue")]

    y_labels[pos0:pos0] = [adjust0]

    x_labels[pos0:pos0] = ['costOfRevenue']
    req_measures[pos0:pos0] = ['relative']

    adjust1 = y_labels[x_labels.index("operatingIncome")] - y_labels[
        x_labels.index("grossProfit")]

    y_labels[3:3] = [adjust1]

    x_labels[3:3] = ['operatingExpense']
    req_measures[3:3] = ['relative']

    pos2 = 5
    adjust2 = y_labels[x_labels.index("incomeBeforeTax")] - y_labels[
        x_labels.index("operatingIncome")]
    y_labels[pos2:pos2] = [adjust2]
    x_labels[pos2:pos2] = ['interestExpense']
    req_measures[pos2:pos2] = ['relative']

    pos3 = 7
    adjust3 = y_labels[x_labels.index("netIncome")] - y_labels[x_labels.index(
        "incomeBeforeTax")]
    y_labels[pos3:pos3] = [adjust3]
    x_labels[pos3:pos3] = ['taxExpense']
    req_measures[pos3:pos3] = ['relative']

    # Graph
    import plotly.graph_objects as go
    fig = go.Figure(
        go.Waterfall(
            name="20",
            orientation="v",
            measure=req_measures,
            x=x_labels,
            textposition="outside",
            # text=["+60", "+80", "", "-40", "-20", "Total"],
            y=y_labels,
            connector={"line": {
                "color": "rgb(63, 63, 63)"
            }},
        ))
    # title_ = "Balance Sheet {}".format(option_slctd2)
    # fig.update_layout(
    #     title=title_,
    #
    # )
    cht1_title = 'Income Statement for {}'.format(option_slctd3)
    # layout = Layout(paper_bgcolor='rgb(0,0,0,0',plot_bgcolor='rgb(0,0,0,0')
    fig.update_layout(
        title=cht1_title,
        xaxis_title="Content",
        yaxis_title="Value",
        # showlegend=True,
        width=700,
        height=500,
        template='plotly_dark')
    return fig
Beispiel #29
0
confirmados_age_m = melter(df, df.columns[23:40:2], 'data_dados')

total_confirmed = list(df_dict['confirmados'].values())[-1]

total_deaths = list(df_dict['obitos'].values())[-1]

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

fig_confirmados_age_f = px.line(confirmados_age_f, x='data_dados', y='value', color='variable')

fig_confirmados_age_m = px.line(confirmados_age_m, x='data_dados', y='value', color='variable')

waterfall_fig = go.Figure(go.Waterfall(x=df['data_dados'], y=df['confirmados_novos']))

app.layout = html.Div([
    html.H1('Portugal COVID Tracker'),
    html.Div([
        html.Div('Total confirmed: %d' % total_confirmed),
        html.Div('Total deaths: %d' % total_deaths)
    ]),
    html.Div([
        dcc.Checklist(
            id='radio_conf',
            options=[{'label' : i, 'value': 'confirmados_' + i} for i in ['arsnorte', 'arscentro', 'arslvt', 'arsalentejo', 'arsalgarve', 'acores', 'madeira']],
            value=['confirmados_arslvt']
            ),
        dcc.Graph(id='line-graph'),
        html.Div([
dcc.Markdown('''The next graph is a waterfall chart that shows the last 12 month movements by industry.

This way you can quickly see what has been growing (green) vs. going backwards (red) which provides a good starting point for a deep dive analysis. '''),



html.Div([html.H3("Australian GDP Year on Year Chain Volume Measure Movements by Industry")], style={"textAlign": "center"}),
html.Div([html.H4("(Last 12 months from Decemeber 2019 to Previous 12 months)")], style={"textAlign": "center"}),
	dcc.Graph(
	figure= go.Figure(
		data=[
			go.Waterfall(
					orientation = 'h',
					measure=measure,
					x=x,
					y=y,
					connector=connector
					)
				],

				layout = layoutWF
				
				)
			), dcc.Markdown('''Hopefully, with these two graphs you gain a quicker insight into what’s happening in the Australian economy over the longer term (compared to what’s normally reported).
			 I will endeavour to keep this up to date as new figures from the ABS is released. ''')
		]
	)