Esempio n. 1
0
def plot_count_ARPU(df, window_type):
    if window_type == "Days":
        df1 = df.resample("D", on="install_time").ARPU.sum()
        df2 = df.resample("D", on="install_time").user_id.count()
    else:
        df1 = df.resample("W", on="install_time").ARPU.sum()
        df2 = df.resample("W", on="install_time").user_id.count()

    fig_count = px.area(df2,
                        x=df2.index,
                        y=df2.values,
                        title="Installations by:" + window_type,
                        color_discrete_sequence=colors)
    fig_count.update_xaxes(title_text=window_type)
    fig_count.update_yaxes(title_text='Installation counts')
    fig_count.update_layout(plot_bgcolor="#fbfbfb")
    fig_count.update_yaxes(showgrid=True, gridwidth=1, gridcolor='#d4d4d4')

    fig_ARPU = px.area(df1,
                       x=df1.index,
                       y=df1.values,
                       title="Income by:" + window_type,
                       color_discrete_sequence=colors)
    fig_ARPU.update_xaxes(title_text=window_type)
    fig_ARPU.update_yaxes(title_text='ARPU Sum')
    fig_ARPU.update_layout(plot_bgcolor="#fbfbfb")
    fig_ARPU.update_yaxes(showgrid=True, gridwidth=1, gridcolor='#d4d4d4')

    return fig_count, fig_ARPU
Esempio n. 2
0
def update_charts(draw_type, contents, name, value):
    ctx = dash.callback_context
    global DATA
    global TRIGER
    if ctx.inputs['my-slider.value'] is not None:
        TRIGER = value
        DATA = données(DATA)

    if ctx.inputs['upload-data.contents'] is not None:
        children = parse_contents(contents, name)
        data = données(children)
        DATA = data
        if ctx.inputs['type-filter.value'] is not None:
            mask = ((DATA.taglist == draw_type))
            filtered_data = DATA.loc[mask, :]
            drawup_figure = px.area(filtered_data,
                                    x=filtered_data['date'],
                                    y=filtered_data[draw_type])
        else:
            drawup_figure = {}

    elif ctx.inputs['type-filter.value'] is not None:
        mask = ((DATA.taglist == draw_type))
        filtered_data = DATA.loc[mask, :]
        drawup_figure = px.area(filtered_data,
                                x=filtered_data['date'],
                                y=filtered_data[draw_type])
    else:
        drawup_figure = {}

    return drawup_figure
Esempio n. 3
0
def update_figure(comboDigestores, interval_component):
    datos = readDB()
    df = pd.DataFrame.from_records(
        datos, columns=["FOS", "TAC", "FOS/TAC", "Fecha", "dige_id"])
    filDig = 1
    if comboDigestores == "Principal":
        filDig = 1
    elif comboDigestores == "Secundario":
        filDig = 2
    filtered_df = df[df.dige_id == filDig]
    fig1 = px.area(filtered_df,
                   x="Fecha",
                   y="FOS",
                   color_discrete_sequence=["yellow"])
    fig2 = px.area(filtered_df,
                   x="Fecha",
                   y="TAC",
                   color_discrete_sequence=["blue"])
    fig3 = px.area(filtered_df,
                   x="Fecha",
                   y="FOS/TAC",
                   color_discrete_sequence=["green"])
    fig1.update_layout(transition_duration=500)
    fig2.update_layout(transition_duration=500)
    fig3.update_layout(transition_duration=500)
    return fig1, fig2, fig3
Esempio n. 4
0
def area_graph():
    st.subheader(
        "Trades (Import or Export) strength could be analyzed using AREA GRAPH"
    )
    st.subheader("Area Plot of Malaysia's Trade Strength from 2013 to 2019")
    sitc = st.sidebar.selectbox('SITC:', ['SITC 1 DIGIT', 'SITC 2 DIGIT'])
    if sitc == 'SITC 1 DIGIT':
        df_sitc_1 = df.groupby(['SITC 1 DIGIT',
                                'YEAR'])[show].agg(['sum']).reset_index()
        df_sitc_1 = df_sitc_1.merge(sitc_1, on='SITC 1 DIGIT')
        fig = px.area(df_sitc_1, x="YEAR", y="sum", color="1D DESC")
        fig.update_layout(height=600, width=900)
    else:
        df_sitc_1 = df.groupby(['SITC 2 DIGIT',
                                'YEAR'])[show].agg(['sum']).reset_index()
        df_sitc_1 = df_sitc_1.merge(sitc_2, on='SITC 2 DIGIT')
        fig = px.area(df_sitc_1, x="YEAR", y="sum", color="2D DESC")
        fig.update_layout(showlegend=False, height=600, width=900)
    fig.update_layout(
        title_text="Trade Performance of Malaysia from 2013 to 2019 based on {}"
        .format(show.split()[0]))
    st.plotly_chart(fig)

    st.subheader(
        "Revealed Comparative Advantage measures (RCA) of Malaysia's Goods from 2013 to 2019"
    )
    st.text(
        'This is a measure of how a country’s exports compare to those of a bigger group, such as a region or the rest of the world. For example, if a country’s RCA in wheat is high (typically greater than one), that means wheat makes up a higher share of that country’s total exports than it does of the world’s exports'
    )
    rca_df = rca.transpose().rename(columns=rca.transpose().iloc[0])
    rca_df.columns = rca_df.columns.rename('Product')
    rca_df = rca_df[1:]
    fig2 = px.area(rca_df, facet_col="Product", facet_col_wrap=2)
    fig2.layout.update(showlegend=False)
    st.plotly_chart(fig2)
Esempio n. 5
0
def area_graph():
    st.subheader("Area Plot of Malaysia's Trade Performance from 2013 to 2019")
    sitc = st.sidebar.selectbox('SITC:', ['SITC 1 DIGIT', 'SITC 2 DIGIT'])
    if sitc == 'SITC 1 DIGIT':
        df_sitc_1 = df.groupby(['SITC 1 DIGIT', 'YEAR'])[show].agg(['sum']).reset_index()
        df_sitc_1 = df_sitc_1.merge(sitc_1, on='SITC 1 DIGIT')
        fig = px.area(df_sitc_1, x="YEAR", y="sum", color="1D DESC")
        fig.update_layout(height=600, width=900)
    else:
        df_sitc_1 = df.groupby(['SITC 2 DIGIT', 'YEAR'])[show].agg(['sum']).reset_index()
        df_sitc_1 = df_sitc_1.merge(sitc_2, on='SITC 2 DIGIT')
        fig = px.area(df_sitc_1, x="YEAR", y="sum", color="2D DESC")
        fig.update_layout(showlegend=False, height=600, width=900)
    fig.update_layout(title_text="Trade Performance of Malaysia from 2013 to 2019 based on {}".format(show.split()[0]))
    st.plotly_chart(fig)
Esempio n. 6
0
def plot(data_points: list,
         height: int = 38,
         width: int = 95,
         top_margin: int = 0,
         left_margin: int = 0,
         bottom_margin: int = 0,
         right_margin: int = 0,
         title: str = ""):
    # image width  = width - left_margin - right_margin
    # image height = height - top_margin - bottom_margin
    fig = px.area(
        pd.DataFrame(data_points),
        height=height,
        width=width,
        title=title,
        range_y=[0, max(data_points)],
    )
    fig.update_traces(line=dict(width=2), line_color='#92acc8')
    fig.update_xaxes(visible=False, fixedrange=True)
    fig.update_yaxes(visible=False, fixedrange=True)
    fig.update_layout(annotations=[], overwrite=True)
    fig.update_layout(showlegend=False,
                      plot_bgcolor="white",
                      margin=dict(t=top_margin,
                                  l=left_margin,
                                  b=bottom_margin,
                                  r=right_margin))
    fig.write_image("images/repository_size.png")
Esempio n. 7
0
def prices(product_name):
    df = pd.read_csv('pricing/assets/historical_pricing.csv')
    df_copy = df.copy()

    product_df = df_copy.loc[df['NAME'] == product_name]
    x = product_df['DATE'].to_list()
    y = product_df['PRICE'].to_list()

    # fig = px.line(df, x, y)

    fig = px.area(df, x="DATE", y="PRICE")

    # https://plotly.com/python/reference/layout/#layout-paper_bgcolor

    colors = {
    'background': 'rgba(0,0,0,0)',
    'paper': 'rgba(0,0,0,0)',
    'text': 'black',
    'colorway': 'red'
    }
    fig.update_layout(
    plot_bgcolor=colors['background'], # background
    paper_bgcolor=colors['paper'],     # graph area total div
    font_color=colors['text'],         # text
    colorway=(colors['colorway'], colors['colorway'])
    )

    fig.update_traces(line_color='red')
    fig.update_xaxes(rangeslider_visible=True)

    return fig
Esempio n. 8
0
    def show_evolution_norm(self,
                            figsize=(15, 4),
                            plotly=True,
                            show=True,
                            return_plot=False):

        # Compute proportion
        states_norm = self._normalize()

        if plotly:
            states_plotly = self._melt(states_norm)
            fig = px.area(states_plotly,
                          x="days",
                          y="value",
                          line_group="compartment",
                          color="compartment")
            if return_plot:
                return fig
            else:
                fig.show()
        else:
            # Plot
            if show:
                states_norm.plot(kind="area", figsize=figsize)
                plt.show()
Esempio n. 9
0
def plot_cumsum(pca):
    exp_var_cumul = np.cumsum(pca.explained_variance_ratio_)
    fig = px.area(
        x=range(1, exp_var_cumul.shape[0] + 1),
        y=exp_var_cumul,
        labels={"x": "# Components", "y": "Explained Variance"})
    fig.show()
Esempio n. 10
0
    def viz(dt,stock,sec):

        fig = px.area(dt)

        fig.update_xaxes(
            title_text = 'Date',
            rangeslider_visible = True,
            rangeselector = dict(
                buttons = list([
                    dict(count = 1, label = '1M', step = 'month', stepmode = 'backward'),
                    dict(count = 6, label = '6M', step = 'month', stepmode = 'backward'),
                    dict(count = 1, label = 'YTD', step = 'year', stepmode = 'todate'),
                    dict(count = 1, label = '1Y', step = 'year', stepmode = 'backward'),
                    dict(step = 'all')])))

        fig.update_yaxes(title_text = 'FB Close Price', tickprefix = '$')
        fig.update_layout(showlegend = False,
            title = {
                'text': f'{stock} Share Price',
                'y':0.9,
                'x':0.5,
                'xanchor': 'center',
                'yanchor': 'top'})

        sec.plotly_chart(fig)
Esempio n. 11
0
def headcount_plot(data_frame):
    """Make a line plot of headcount.

    The data frame should have start_date and headcount columns
    """
    if len(data_frame) == 0:
        fig = go.Figure()
    else:
        fig = px.area(data_frame,
                      x="start_date",
                      y="headcount",
                      color="organization",
                      line_shape="hv")

    fig.update_layout(
        xaxis_title="Reporting Period Start Date",
        yaxis_title="",
        title_text="Number of Tockers vs. Time",
        hovermode="x",
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1,
        ),
    )
    fig.update_traces(hovertemplate="%{y}")

    plot_div = plot(fig, output_type="div", include_plotlyjs=False)
    return plot_div
Esempio n. 12
0
    def orders_over_time(self):
        st.markdown('''
        # Advanced Order Filter
        
        This page shows advanced filters, fine-tunable using the left panel.
        
        It's useful when wanting to find specific statistics about orders 
        by time, location or order type.
        ''')

        st.markdown('''
        ## Orders by Country
        ''')

        df = self.df.groupby(
            [pd.Grouper('COUNTRY'),
             self.df['ORDERDATE'].dt.strftime('%Y-%m')])['SALES'].sum()
        df = df.sort_values(ascending=False)
        df = df.reset_index()
        df = df.rename({'level_0': 'COUNTRY', 'level_1': 'ORDERDATE'})

        fig = px.area(df,
                      x="ORDERDATE",
                      y="SALES",
                      color="COUNTRY",
                      line_group="COUNTRY")
        st.plotly_chart(fig, use_container_width=True)
Esempio n. 13
0
def update_index_df(n, sel_col):

    df_index = query_mongo("index", "index_level_1000")

    dff = df_index.copy()
    dff = dff.loc[dff["Date"] > "2016-09-30"]
    dff_last = dff.tail(2)
    dff_y = dff_last[dff_last['Date'] ==
                     dff_last['Date'].min()]['Index Value'].values[0]
    dff_t = dff_last[dff_last['Date'] ==
                     dff_last['Date'].max()]['Index Value'].values[0]

    variation = (dff_t >= dff_y)
    dff["Var"] = variation

    index_area = area(data_frame=dff,
                      x="Date",
                      y="Index Value",
                      labels={
                          "value": "",
                          "Index Value": "",
                          "Date": ""
                      },
                      template=sel_col,
                      title='Crypto Index Level (USD)',
                      color="Var",
                      color_discrete_map={
                          False: '#FD3216',
                          True: '#1CA71C',
                      })
    index_area.update_layout(showlegend=False)

    index_area.update_yaxes(tickprefix="$")

    return index_area
def area_chart(dataframe, x, y):
    '''
    Función para generar gráficas lineales con area_chart
    '''
    fig = px.area(dataframe, x=x, y=y, title='Suscriptores De Internet Venezuela')
    fig.update_xaxes(rangeslider_visible=True)
    fig.update_yaxes(title=None)
    fig.update_layout(
            hovermode='x',
            paper_bgcolor='#212529',
            plot_bgcolor='#212529',
            font=dict(color='white', size=12),
            width=700,
            height=500,
            legend=dict(
                orientation="h",
                yanchor="bottom",
                y=1.02,
                xanchor="right",
                x=1
                )
            )

    graph_json = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    return graph_json
Esempio n. 15
0
def update_graph(country, stat):
    filtered_df = df.loc[df['Country']==country]
    filtered_df = filtered_df[::-1]  # without this the graph is backwards
    date_list = filtered_df['Date'].to_list()
    date_list = date_list[::30]
    print(date_list)# Only get every 4th value - we're going to use this for showing fewer tickers
    filtered_df['colour']='orange'
    colormap = {'orange':'orange', 'lightblue':'lightblue','darkskyblue':'darkskyblue'}
    fig = px.area(filtered_df, x='Date', y=stat, template='plotly_dark',color='colour',color_discrete_map=colormap,
                  title= 'Worldwide COVID-19 Tracker')
    fig.update_layout(title_font_family='Arial')
    fig.update_xaxes(tickangle=45, tickfont=dict(family='Arial', size=10))
    fig.update_xaxes(showgrid=False) # hide x-axis gridlines
    fig.update_yaxes(showgrid=True)
    fig.update_layout(showlegend=False) # hide legend
    fig.update_layout(width=600, height=450)
    fig.update_layout(
        xaxis=dict(
            tickmode='array',
            tickvals=date_list,
            ticktext=date_list
        ),
            plot_bgcolor='rgba(0,0,0,0)',
            paper_bgcolor='rgba(0,0,0,0)'
    )

    return fig
Esempio n. 16
0
    def create_generation_plot(self, market_result, show_plot=True, filepath=None):
        """Create Generation plot.
        """
        gen = market_result.generation()
        if "tech" in market_result.data.plants.columns:
            gen = pd.merge(gen, market_result.data.plants.tech, left_on="p", right_index=True)
        else:
            gen["tech"] = gen.plant_type
        gen = gen[["fuel", "tech", "t", "G"]].groupby(["fuel", "tech", "t"]).sum().reset_index()
        gen_colors = self.color_map(gen)
        gen = pd.merge(gen, gen_colors, on=["fuel", "tech"])
        gen.loc[:, "G"] *= 1/1000
        fig = px.area(gen, x="t", y="G", color="name", 
                    color_discrete_map=gen_colors[["color", "name"]].set_index("name").color.to_dict())

        fig.layout.xaxis.title="Time"
        fig.layout.yaxis.title="Generation/Load [GW]"

        inf = market_result.infeasibility(drop_zero=False)
        inf["infeasibility"] = inf.pos - inf.neg
        inf = inf[["t", "infeasibility"]].groupby("t").sum()/1000

        d = pd.merge(market_result.demand(), market_result.data.net_export, left_on=["t", "n"], right_on=["timestep", "node"])
        d = d[["t", "demand_el", "D_ph", "D_es", "net_export"]].groupby("t").sum()/1000
        d.loc[:, "demand_el"] -= (d.net_export)
        d = d.loc[market_result.model_horizon, :]

        fig.add_trace(go.Scatter(x=d.index, y=d.demand_el - inf.infeasibility, line=dict(color="#000000"), name="demand")) 
        fig.add_trace(go.Scatter(x=d.index, y=d.demand_el - inf.infeasibility + d.D_es + d.D_ph, fill='tonexty', mode= 'none', fillcolor="#BFBDE5", name="storage charging"))
        if show_plot:
            plot(fig)
        if filepath:
            fig.write_html(str(filepath))
def update_figure_valadds_total(services_valadd_trend, mining_valadd_trend, manufacturing_valadd_trend, gas_water_waste_valadd_trend, 
                                construction_valadd_trend, com_transp_valadd_trend, agrifor_valadd_trend, 
                                electricity_growth_trend, tab):
    df_select = df_full[(df_full['geo']==tab) & (df_full['year']>=2009) & (df_full['sector']!="Overall")]
    ### Value added calculation:
    ### For value added trends, we need picker 1 plus picker value 
    df_select.loc[(df_select['sector']=='Services') & (df_select['yrs_since_final_obs']>0),'ind_val_add_output'] = df_select['ind_val_add_2019_bln_finaly']*np.power((1+(services_valadd_trend/100)),df_select['yrs_since_final_obs'])
    df_select.loc[(df_select['sector']=='Mining') & (df_select['yrs_since_final_obs']>0),'ind_val_add_output'] = df_select['ind_val_add_2019_bln_finaly']*np.power((1+(mining_valadd_trend/100)),df_select['yrs_since_final_obs'])
    df_select.loc[(df_select['sector']=='Manufacturing') & (df_select['yrs_since_final_obs']>0),'ind_val_add_output'] = df_select['ind_val_add_2019_bln_finaly']*np.power((1+(manufacturing_valadd_trend/100)),df_select['yrs_since_final_obs'])
    df_select.loc[(df_select['sector']=='Gas, Water & Waste Services') & (df_select['yrs_since_final_obs']>0),'ind_val_add_output'] = df_select['ind_val_add_2019_bln_finaly']*np.power((1+(gas_water_waste_valadd_trend/100)),df_select['yrs_since_final_obs'])
    df_select.loc[(df_select['sector']=='Construction') & (df_select['yrs_since_final_obs']>0),'ind_val_add_output'] = df_select['ind_val_add_2019_bln_finaly']*np.power((1+(construction_valadd_trend/100)),df_select['yrs_since_final_obs'])
    df_select.loc[(df_select['sector']=='Commercial Transport') & (df_select['yrs_since_final_obs']>0),'ind_val_add_output'] = df_select['ind_val_add_2019_bln_finaly']*np.power((1+(com_transp_valadd_trend/100)),df_select['yrs_since_final_obs'])
    df_select.loc[(df_select['sector']=='Agriculture & Forestry') & (df_select['yrs_since_final_obs']>0),'ind_val_add_output'] = df_select['ind_val_add_2019_bln_finaly']*np.power((1+(agrifor_valadd_trend/100)),df_select['yrs_since_final_obs'])
    ### Note electricity generation here has added value grow together with value added
    df_select.loc[(df_select['sector']=='Electricity generation') & (df_select['yrs_since_final_obs']>0),'ind_val_add_output'] = df_select['ind_val_add_2019_bln_finaly']*np.power((1+(electricity_growth_trend/100)),df_select['yrs_since_final_obs'])
    
    ### Redefine value added figure again, but with dynamic input
    df_select_val_add = df_select[df_select.sector != 'LULUCF']
    df_select_val_add = df_select_val_add[df_select_val_add .sector != 'Residential']
    fig_added_value_total = px.area(df_select_val_add, x="year", y="ind_val_add_output", color="sector",
                                    color_discrete_sequence=['#D62728', '#2CA02C', '#9467BD', '#8C564B', '#E377C2', '#BCBD22', '#7F7F7F', '#17BECF'],
                                    labels={"year": "", "ind_val_add_output": "Value added (billion 2019 AUD)<sub> </sub>"},
                                    title="Value added by industry")
    fig_added_value_total.update_layout(transition_duration=500,
                                        template="plotly_white",
                                        legend_traceorder="reversed",
                                        title_font_color="#1F77B4",
                                        title_font_size=18,
                                        title_font_family="Rockwell",
                                        title_x = 0.02,
                                        margin=dict(t=40, r=0, b=0, l=60, pad=0))
    fig_added_value_total.update_xaxes(showline=True, linewidth=1, linecolor='black', gridcolor='rgba(149, 165, 166, 0.6)', mirror=True)
    fig_added_value_total.update_yaxes(showline=True, linewidth=1, linecolor='black', gridcolor='rgba(149, 165, 166, 0.6)', mirror=True)
    return fig_added_value_total
def update_figure(agri_emis_trend, elec_emis_trend, lulucf_emis_trend):
    ### Emissions output agriculutre: emissions levels at last observation, minus number of years since final observation *annual emission reductions. Second line si so they cannot go negative
    df_nat.loc[(df_nat['sector'] == 'Agriculture') &
               (df_nat['yrs_since_final_obs'] > 0),
               'emissions_MtCo2_output'] = df_nat[
                   'emissions_MtCo2_finaly'] + agri_emis_trend * df_nat[
                       'yrs_since_final_obs']
    df_nat.loc[(df_nat['sector'] == 'Agriculture') &
               (df_nat['emissions_MtCo2_output'] < 0),
               'emissions_MtCo2_output'] = 0
    ### Emissions output electricity: emissions levels at last observation, minus number of years since final observation *annual emission reductions. Second line si so they cannot go negative
    df_nat.loc[(df_nat['sector'] == 'Electricity generation') &
               (df_nat['yrs_since_final_obs'] > 0),
               'emissions_MtCo2_output'] = df_nat[
                   'emissions_MtCo2_finaly'] + elec_emis_trend * df_nat[
                       'yrs_since_final_obs']
    df_nat.loc[(df_nat['sector'] == 'Electricity generation') &
               (df_nat['emissions_MtCo2_output'] < 0),
               'emissions_MtCo2_output'] = 0
    ### Emissions output LULUCF: emissions levels at last observation, minus number of years since final observation *annual emission reductions
    df_nat.loc[(df_nat['sector'] == 'LULUCF') &
               (df_nat['yrs_since_final_obs'] > 0),
               'emissions_MtCo2_output'] = df_nat[
                   'emissions_MtCo2_finaly'] + lulucf_emis_trend * df_nat[
                       'yrs_since_final_obs']

    ### Redefine figure again, but with dynamic input
    fig_emissions_total = px.area(df_nat,
                                  x="year",
                                  y="emissions_MtCo2_output",
                                  color="sector")
    fig_emissions_total.update_layout(transition_duration=500)

    return fig_emissions_total
def plot_capacity_line():
    data = make_cumulative_by_district()
    fig = px.area(
        data,
        x="Commissioned",
        y="Cumulative",
        color="Region",
        title='Cumulative installed capacity (kWp) over time',
        line_group="PLN_AREA_N",
        labels={
            "Commissioned": "Date",
            "Cumulative": "Cumulative installed capacity (kWp)"
        },
    )
    fig.update_xaxes(
        rangeslider_visible=True,
        rangeselector=dict(buttons=list([
            dict(count=5, label="5y", step="year", stepmode="backward"),
            dict(count=2, label="2y", step="year", stepmode="backward"),
            dict(count=1, label="1y", step="year", stepmode="backward"),
            dict(count=1, label="YTD", step="year", stepmode="todate"),
            dict(step="all")
        ])))
    fig.show()
    pio.write_html(fig, file='cumulative_installations.html', auto_open=True)
Esempio n. 20
0
def get_figure2(explained_var):
    print("COMP")

    # set which points are selected with the `selectedpoints` property
    # and style those points with the `selected` and `unselected`
    # attribute. see
    # https://medium.com/@plotlygraphs/notes-from-the-latest-plotly-js-release-b035a5b43e21

    exp_var_cumul = np.cumsum(explained_var)

    fig = px.area(x=range(1, exp_var_cumul.shape[0] + 1),
                  y=exp_var_cumul,
                  labels={
                      "x": "# Components",
                      "y": "Explained Variance"
                  })

    #fig = px.histogram(selectedpoints)
    #fig.update_layout(autosize=True,margin=dict(l=30, r=30, b=20, t=40),hovermode="closest",plot_bgcolor="#F9F9F9",paper_bgcolor="#E9E9E9",legend=dict(font=dict(size=10), orientation="h"))
    #fig = px.scatter(df, x=df[x_col], y=df[y_col], text=df.index)
    #print("HISTO POINTS")
    #print(selectedpoints)

    #fig.update_layout(margin={'l': 20, 'r': 0, 'b': 15, 't': 5}, dragmode='select', hovermode=False)

    #fig.add_shape(dict({'type': 'rect',
    #'line': { 'width': 1, 'dash': 'dot', 'color': 'darkgrey' }},
    #**selection_bounds))
    return fig
Esempio n. 21
0
def time_series(data_init,data_end,is_table,is_plot):
    df = load_data(data_init,data_end)
    title = f'Evolução energética de {data_init} a {data_end}'
    if (df.size > 0):
        if is_plot:
            fig = px.area(df)
            fig.update_yaxes(
                title_text = "Energia/kWh" 
            )
            fig.update_layout(
                title=dict(
                    text=title,
                    xanchor="center",
                    yanchor="top",
                    x=0.5,
                    y=0.93
                ),
                legend_title = '',
                legend=dict(
                    orientation="h",
                    yanchor="top",
                    xanchor="center",
                    x = 0.5,
                    y=-0.2,
                    itemwidth=40
                )
            )
            st.plotly_chart(fig)
        if is_table:
            st.dataframe(df.style.format("{:.2f}"))
    else: 
        st.write("Periodo sem dados.")
Esempio n. 22
0
def plot_stock_price_area_chart(stock_prices: pd.DataFrame) -> None:
    c_area = px.area(stock_prices['Close'], title='Stock Price')
    c_area.update_xaxes(
        title_text='Date',
        rangeslider_visible=True,
        rangeselector=dict(buttons=list([
            dict(count=1, label='1M', step='month', stepmode='backward'),
            dict(count=6, label='6M', step='month', stepmode='backward'),
            dict(count=1, label='YTD', step='year', stepmode='todate'),
            dict(count=1, label='1Y', step='year', stepmode='backward'),
            dict(count=3, label='3Y', step='year', stepmode='backward'),
            dict(count=5, label='5Y', step='year', stepmode='backward'),
            dict(step='all')
        ])))

    c_area.update_yaxes(title_text='Close Price', tickprefix='$')
    c_area.update_layout(showlegend=False,
                         title={
                             'text': 'Closing Share Price',
                             'y': 0.9,
                             'x': 0.5,
                             'xanchor': 'center',
                             'yanchor': 'top'
                         })

    return c_area
Esempio n. 23
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--csv_file_path')
    args = parser.parse_args()

    st = TokyoCovid19Stat(args.csv_file_path)

    cases_by_age = melt(st.cases_by_age,
                        value_columns=TokyoCovid19Stat.AGECOLNAMES,
                        var_name='Age')

    sma_by_age = melt(sma(st.cases_by_age),
                      value_columns=TokyoCovid19Stat.AGECOLNAMES,
                      var_name='Age')

    title = 'Tokyo Covid-19 New Cases By Age'
    fig = px.area(cases_by_age, x='Date', y='Cases', color='Age', title=title)
    py.plot(fig, filename=title, auto_open=False)

    title = 'Tokyo Covid-19 New Cases 7-day Moving Average By Age'
    fig = px.line(sma_by_age, x='Date', y='Cases', color='Age', title=title)
    fig.add_bar(x=st.cases.index,
                y=st.cases['Cases'],
                name='Raw Total',
                marker=dict(color='#dddddd'))
    py.plot(fig, filename=title, auto_open=False)
Esempio n. 24
0
def update_app_ui3(chart_dp_value, search, year_selector):

    chart_df = pd.DataFrame()  #same as the above
    year_range = [x for x in range(year_selector[0], year_selector[1] + 1)]

    for i in year_range:
        tmpdf = pd.DataFrame(df[df['iyear'] == i])
        chart_df = chart_df.append(tmpdf)

    if chart_dp_value is not None:
        if search is not None:
            chart_df = chart_df.groupby(
                'iyear')[chart_dp_value].value_counts().reset_index(
                    name='count'
                )  #to merge the data using count of the region occured
            chart_df = chart_df[chart_df[chart_dp_value].str.contains(
                search, case=False)]  #to filter the data using search bar
        else:
            chart_df = chart_df.groupby('iyear')[chart_dp_value].value_counts(
            ).reset_index(name='count')

            print('chart_df is', chart_df)

    else:
        raise PreventUpdate

    chartFigure = px.area(chart_df,
                          x='iyear',
                          y='count',
                          color=chart_dp_value,
                          height=500)
    fig = chartFigure

    return fig
def unemploymentviz(city, state, metric='unemployment_rate'):
    """
    Visualize historical population metrics from 2010 to 2018 for one city 

    ### Query Parameters:

    - `metric`: 'unemployment_rank', 'rank'; default='unemployment_rate',case sensitive, 
    unemployment_rate in percentage (ex: Spokane - 5.5% of city population unemployed), 
    rank in how the city compares to other metropolitan areas (ex: lower the better, higher means
    more unemployment)

    - `city`: [city name], case sensitive(ex: Birmingham)

    - `state `: [state abbreviation], 2-letters; case sensitive (ex: AL) 

    ### Response
    JSON string to render with react-plotly.js
    """
    df = pd.read_csv(historical_unemp_filepath, encoding='utf-8')
    subset = df[(df.city == city) & (df.state == state)]
    fig = px.area(subset,
                  x='year',
                  y=metric,
                  title=f'{metric} in {city},{state}')
    return fig.to_json()
Esempio n. 26
0
def fig_c002(regions=["Lombardia", "Veneto"], norm="fraction"):
    value_name = "Valore % sul Tot." if norm == "fraction" else "Valore"
    yformat = ".1%" if norm == "fraction" else ".0"
    data = get_pop_covid_regions()
    covid_lomb_ven = data[data.region.isin(regions)]
    covid_lomb_ven = covid_lomb_ven.melt(
        id_vars=["time", "region"],
        value_vars=["n_home_quarantine", "n_hospitalized", "n_intensive_care"],
        var_name="Variabile",
        value_name=value_name,
    )

    covid_lomb_ven["Variabile"] = covid_lomb_ven["Variabile"].replace(labels)

    fig = px.area(
        covid_lomb_ven.sort_values(by=["time", "Variabile"], ascending=False),
        x="time",
        y=value_name,
        color="Variabile",
        color_discrete_sequence=["#EF553B", "#FF7F0E", "#54A24B"],
        facet_col="region",
        labels=labels,
        groupnorm=norm,
        template="plotly_white",
    )
    fig.update_xaxes(title=None)
    fig.add_annotation(
        font=dict(size=9, color="grey"),
        showarrow=False,
        yref="paper",
        xref="paper",
        text="Fonte: ISTAT, Dipartimento di Protezione Civile Italiana",
        y=-0.15,
        yanchor="top",
    )
    fig.update_layout(
        title=dict(
            text=f"<br><b>Composizione dei Casi COVID-19 Attivi:"
            " Lombardia e Veneto</b></br>"
            f'<span style="font-size: 12px">{value_name} - Clicca sulle Voci '
            "nella Legenda per Selezionare o Deselezionare</span>",
            x=0.5,
            y=0.98,
        ),
        legend=dict(orientation="h", y=-0.2, yanchor="top", title=None),
        yaxis=dict(tickformat=yformat),
        margin={
            "l": 60,
            "r": 30,
            "t": 130,
            "b": 100,
            "autoexpand": False
        },
        dragmode=False,
        width=650,
        height=450,
    )
    watermark(fig)

    return fig
Esempio n. 27
0
def update_graph_prediction(age, scan, visual, loading, model_name):
    model = models[model_name]

    future_ages = [age + offset for offset in np.arange(0, 10, 1)]

    samples = np.hstack([
        oh_enc.transform([[visual]] * 10),
        np.array([[age, scan, loading] for age in future_ages]),
    ])

    preds = pd.DataFrame(sp.special.softmax(model.decision_function(samples),
                                            axis=1),
                         columns=model.classes_)

    fig = px.area(preds,
                  labels={
                      'value': 'Softmax Score',
                      'index': 'Number of years from present',
                      'variable': 'Oil Leak'
                  },
                  title='Predicted Future Risk of Oil Leak')

    fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', font_color='white')

    return fig
Esempio n. 28
0
def update_charts(selected_stock, selected_metric):
    """Update the price chart and fundamental analysis
    for a selected stock. Inputs are the selected stock and chosen 
    fundamentals metric."""

    ratios = ratio_analysis(selected_stock, api_key)
    prices, ticker = get_prices(ratios, selected_stock)
    company = get_companyname(selected_stock, api_key)

    # fig = make_subplots(rows=2, cols=1, shared_xaxes=True,\
    #                     subplot_titles=(f'{ticker}',\
    #                                     '{} {}'.format(ticker,selected_metric)))
    # fig.append_trace(go.Line(x=prices['date'],y=prices['close'],),row=1,col=1)
    # fig.append_trace(go.Line(x=ratios['date'],y=ratios[selected_metric],),row=2,col=1)

    #plot prices
    price_fig = px.area(prices, x='date', y='close')
    if prices['close'].iloc[0] < prices['close'].iloc[-1]:
        fill = '#98FB98'
    else:
        fill = '#CD5C5C'
    price_fig.update_traces(line_color=fill)
    price_fig.update_layout(margin=dict(l=20, r=20, t=20, b=20),
                            yaxis_title='Closing Price [$]',
                            plot_bgcolor=colors['background'],
                            paper_bgcolor=colors['background'],
                            font_family='monospace',
                            font_color=colors['text'],
                            title={
                                'text': f'{ticker}: {company}',
                                'y': 1,
                                'x': 0.5,
                                'xanchor': 'center',
                                'yanchor': 'top'
                            })

    #plot metrics
    metric_fig = px.line(ratios, x='date', y=selected_metric)
    # fig.update_xaxes(title_text="Date", row=1, col=1)
    # fig.update_xaxes(title_text="Date", row=2, col=1)
    # fig.update_yaxes(title_text="Closing Price",row=1, col=1)
    # fig.update_yaxes(title_text="{}".format(selected_metric), row=2, col=1)
    metric_fig.update_xaxes(
        range=[prices['date'].iloc[0], prices['date'].iloc[-1]])
    metric_fig.update_traces(line_color='#FFFF00')
    metric_fig.update_layout(margin=dict(l=20, r=20, t=20, b=20),
                             plot_bgcolor=colors['background'],
                             paper_bgcolor=colors['background'],
                             font_family='monospace',
                             font_color=colors['text'],
                             title={
                                 'text':
                                 f'{company} ({ticker}) : {selected_metric}',
                                 'y': 1,
                                 'x': 0.5,
                                 'xanchor': 'center',
                                 'yanchor': 'top'
                             })
    return price_fig, metric_fig
Esempio n. 29
0
def plot_cases_per_date(df, ylabel):
    temp = df['Date reported'].value_counts().sort_index().fillna(0).rolling(7).mean()
    fig = px.area(temp,
                  labels = {'value':ylabel, 'index': 'Date reported'},
                  color_discrete_sequence=px.colors.qualitative.D3)
    fig.add_hline(y=500)
    fig.update_layout(showlegend=False)
    return fig
Esempio n. 30
0
def total_hospi_new_out_provinces():
    fig = px.area(df,
                  x="DATE",
                  y="NEW_OUT",
                  color="PROVINCE",
                  title="Number of hospital discharges that day")
    fig.update_layout(template="plotly_white")
    return fig