Esempio n. 1
0
def year_filter(dff, year):
    """ renames columns so selected year doesn't have the year extension ie Amount_2017 """
    return dff.rename(
        columns={
            du.get_col("Amount", year): "Amount",
            du.get_col("Per Capita", year): "Per Capita",
            du.get_col("Per Student", year): "Per Student",
        })
def table_yr(dff, year):
    """ renames columns to display selected year in table """
    return dff.rename(
        columns={
            du.get_col("Amount", year): "Amount",
            du.get_col("Per Capita", year): "Per Capita",
            du.get_col("Population", year): "Population",
        })
def make_stats_table(population, dff_exp, selected, year):
    per_capita = dff_exp[du.get_col("Per Capita",
                                    year)].astype(float).sum() / selected
    total_exp = dff_exp[du.get_col("Amount", year)].astype(float).sum()

    row1 = html.Tr([
        html.Td("{:0,.0f} {}".format(population, "Population"),
                className="text-center"),
    ])
    row2 = html.Tr([
        html.Td(
            "${:0,.0f} {}".format(per_capita, "Per Capita All Categories"),
            className="text-center",
        ),
    ])
    table_body = [html.Tbody([row2, row1])]

    return dbc.Table(
        table_body,
        bordered=False,
        className="table table-sm table-light",
        style={"font-size": "12px"},
    )
def update_mystate(mystate, year, exp_or_rev):
    year = str(year)

    dff = df_exp if exp_or_rev == "Expenditures" else df_rev

    selected = 1  # TODO allow for multiple selected states
    dff = dff[dff["State"] == mystate]
    population = int(df_pop.loc[df_pop["State"] == mystate, int(year)])
    title = year + " My State"

    return (
        make_sunburst(dff, ["State", "Category"], du.get_col("Amount", year),
                      title),
        make_stats_table(population, dff, selected, year),
    )
def update_selected_state(selected_state, year, exp_or_rev):

    year = str(year)
    dff = df_exp if exp_or_rev == "Expenditures" else df_rev

    if selected_state == "USA":
        path = ["USA", "Category"]
        population = df_pop[int(year)].astype(float).sum()
        title = year + " Selected: USA"
        selected = 51  # TODO allow for multiple selected states
    else:
        dff = dff[dff["State"] == selected_state]
        path = ["State", "Category"]
        population = int(df_pop.loc[df_pop["State"] == selected_state,
                                    int(year)])
        title = year + " Selected State"
        selected = 1

    return (
        make_sunburst(dff, path, du.get_col("Amount", year), title),
        make_stats_table(population, dff, selected, year),
    )
def update_map(
    __,
    year,
    state,
    cat,
    subcat,
    local,
    viewport,
    exp_or_rev,
):
    dff_map = df_rev if exp_or_rev == "Revenue" else df_exp
    dff_table = dff_sunburst = dff_map.copy()
    title = " ".join([str(year), exp_or_rev, "Per Capita by State"])
    map_title = title
    sunburst_title = " ".join(
        ["All States ", str(year), exp_or_rev, "Per Capita "])

    all_state_btn = "d-none"
    # filter
    if state != "USA":
        dff_table = (dff_table[dff_table["State"] == state]
                     if state else dff_table[dff_table["State"] == "Alabama"])
        dff_sunburst = dff_table.copy()
        sunburst_title = " ".join([str(year), exp_or_rev, state])
        all_state_btn = ""

    if cat and (cat != "all"):
        dff_table = dff_table[dff_table["Category"] == cat]
        dff_map = dff_map[dff_map["Category"] == cat]
        map_title = " ".join([title, ": ", cat])

    if subcat and (subcat != "all"):
        dff_table = dff_table[dff_table["Description"] == subcat]
        dff_map = dff_map[dff_map["Description"] == subcat]
        map_title = " ".join([title, ": ", subcat])

    # subtotal
    if local:
        dff_table = (dff_table.groupby(
            ["State", "Category", "Description",
             "State/Local"]).sum().reset_index())

    elif subcat:
        dff_table = (dff_table.groupby(["State", "Category",
                                        "Description"]).sum().reset_index())

    elif cat:
        dff_table = dff_table.groupby(["State",
                                       "Category"]).sum().reset_index()

    else:
        dff_table = dff_table.groupby(["State"]).sum().reset_index()

    dff_table["sparkline"] = du.make_sparkline(dff_table, "Per Capita",
                                               du.YEARS)
    dff_table = table_yr(dff_table, str(year))

    # update sunburst
    figure = make_sunburst(
        dff_sunburst,
        ["Category", "Description", "State/Local"],
        du.get_col("Amount", str(year)),
        sunburst_title,
    )

    bar_charts = []
    if len(dff_table["State"].unique()) > 1:
        bar_charts = du.make_bar_charts(pd.DataFrame(viewport), "Per Capita",
                                        "State")

    if dff_map.empty:
        return [], [], [], [], all_state_btn

    return (
        make_choropleth(dff_map, map_title, state, str(year)),
        dff_table.to_dict("records"),
        figure,
        bar_charts,
        all_state_btn,
    )
def make_choropleth(dff, title, state, year):
    dff = (dff.groupby(["ST", "State"]).sum().reset_index().sort_values(
        du.get_col("Per Capita", year), ascending=False))
    top3 = (dff.head(3).astype({du.get_col("Per Capita", year):
                                "int"})[["ST",
                                         du.get_col("Per Capita", year)
                                         ]].to_string(index=False,
                                                      header=False).replace(
                                                          "\n", "<br>"))
    bot3 = (dff.tail(3).astype({du.get_col("Per Capita", year):
                                "int"})[["ST",
                                         du.get_col("Per Capita", year)
                                         ]].to_string(index=False,
                                                      header=False).replace(
                                                          "\n", "<br>"))

    fig = go.Figure(data=go.Choropleth(
        locations=dff["ST"],  # Spatial coordinates
        z=dff[du.get_col("Per Capita", year)].astype(
            int),  # Data to be color-coded
        name="Per Capita",
        text=dff["State"],
        locationmode=
        "USA-states",  # set of locations match entries in `locations`
        colorscale="amp",
        autocolorscale=False,
        colorbar_title="USD",
    ))

    # highlights selected state borders
    if state != "USA":
        selected_state = dff[dff.ST == du.state_abbr[state]]
        fig.add_trace(
            go.Choropleth(
                locationmode="USA-states",
                z=selected_state[du.get_col("Per Capita", year)].astype(int),
                locations=[du.state_abbr[state]],
                colorscale=[[0, "rgba(0, 0, 0, 0)"], [1, "rgba(0, 0, 0, 0)"]],
                marker_line_color="#8f97f8",
                marker_line_width=4,
                showscale=False,
                text=[state],
                hovertemplate="%{z:$,.0f} %{text} <extra></extra>",
            ))

    fig.update_traces(
        go.Choropleth(hovertemplate="%{z:$,.0f} %{text} <extra></extra>"))

    fig.update_layout(
        title_text=title,
        title_x=0.5,
        title_xanchor="center",
        title_yanchor="top",
        title_y=1,
        font=dict(size=14),
        geo_scope="usa",  # limite map scope to USA
        margin=go.layout.Margin(b=75, t=20, l=10, r=10),
        yaxis=go.layout.YAxis(tickprefix="$", fixedrange=True),
        xaxis=go.layout.XAxis(fixedrange=True),
        #  paper_bgcolor="#eeeeee",
        annotations=[
            dict(
                x=1,
                y=0.95,
                showarrow=False,
                text="Top 3: <br>" + top3,
                xref="paper",
                yref="paper",
            ),
            dict(
                x=1,
                y=0.05,
                showarrow=False,
                text="Bottom 3: <br>" + bot3,
                xref="paper",
                yref="paper",
            ),
        ],
    )
    return fig
    return dbc.Table(
        table_body,
        bordered=False,
        className="table table-sm table-light",
        style={"font-size": "12px"},
    )


state_sunburst = html.Div([
    dcc.Graph(
        id="sunburst_state",
        figure=make_sunburst(
            df_exp,
            ["USA", "Category"],
            du.get_col("Amount", du.START_YR),
            du.START_YR + " Selected",
        ),
        style={"height": "200px"},
        config={"displayModeBar": False},
    ),
    html.Div(
        id="state_stats",
        children=make_stats_table(df_pop[int(du.START_YR)].astype(float).sum(),
                                  df_exp, 51, du.START_YR),
    ),
], )

USA_sunburst = html.Div([
    dcc.Graph(
        figure=make_sunburst(