示例#1
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
示例#2
0
def fig_a006():
    df = pd.read_csv(
        "https://raw.githubusercontent.com/buildnn/covid-19-ita/master/"
        "data/migrazione_sanitaria_gimbe_2019-06.csv"
    )
    df["Saldo"] = ((df["Crediti"] - df["Debiti"]) / 1000000).round(1)
    df = df.sort_values("Saldo").dropna(subset=["Saldo"])

    fig_a006 = px.bar(
        df,
        y="Regione",
        x="Saldo",
        orientation="h",
        color="Saldo",
        color_continuous_midpoint=0,
        color_continuous_scale="Temps_r",
        width=500,
        height=700,
        range_x=(-450, 810),
        template="plotly_white",
        labels={"Saldo": "Saldo (mln€)"},
        title="<br><b>Saldo per Prestazioni verso Non Residenti</b></br>"
        '<span style="font-size: 12px;">Anno 2017 - Milioni di Euro</span>',
    )
    fig_a006.layout.coloraxis.showscale = False
    fig_a006.update_layout(
        margin={"l": 120, "r": 30, "t": 80, "b": 100, "autoexpand": False},
        legend=dict(orientation="h", y=-0.78, title=None),
        yaxis=dict(title=None),
        xaxis=dict(tickformat="+0", tick0=-400, dtick=200),
        title=dict(x=0.5, y=0.98),
    )
    fig_a006.add_annotation(
        text="<br>Fonte: Osservatorio GIMBE, ACISMOM e OPBG indicano "
        "rispettivamente Ospedale Pediatrico Bambino Gesù <br>e Associazione "
        "dei Cavalieri Italiani del Sovrano Militare Ordine di Malta, "
        "contabilizzati separatamente",
        align="center",
        font=dict(size=9, color="grey"),
        showarrow=False,
        xref="paper",
        yref="paper",
        x=-0.28,
        y=-0.15,
    )

    watermark(fig_a006)

    return fig_a006
示例#3
0
def plot_veneto_lombardy(df, y, title):
    x = "time"

    fig = px.line(
        df.round(2),
        x=x,
        y=y,
        color="region",
        width=600,
        height=400,
        template="plotly_white",
        labels={
            "tot_n_hospitalized_anchored": "N. Ospedalizzati,"
            " 25 Feb = 1",
            "n_intensive_care_anchored": "N. Ricoveri in Terapia Intensiva,"
            " 25 Feb = 1",
            "time": "Data",
            "region": "Regione",
        },
        range_x=(
            pd.to_datetime("2020-02-25"),
            df.time.max() + pd.to_timedelta(10, "D"),
        ),
        line_shape="spline",
    )

    fig.update_traces(line=dict(width=1.0))

    for trace in fig.data:
        name = trace["name"]
        color = trace["line"]["color"]

        lom = df.loc[(df.time == df.time.max()) & (df.region == name)]

        fig.add_trace(
            go.Scatter(
                x=lom[x],
                y=lom[y],
                text=lom["region"],
                textposition="middle right",
                mode="markers+text",
                hoverinfo="skip",
                marker=dict(color=color),
            ))

    fig.update_layout(
        margin={
            "l": 40,
            "r": 20,
            "b": 40,
            "t": 80,
            "autoexpand": False
        },
        title=dict(
            text=title,
            x=0.5,
            y=0.96,
        ),
        xaxis=dict(title=None),
        yaxis_tickformat="20",
        # legend=dict(orientation="h", yanchor="top", y=-.15, title=None),
        showlegend=False,
    )
    fig.add_annotation(
        text="Fonte: Dipartimento di Protezione Civile",
        font=dict(size=9, color="grey"),
        showarrow=False,
        xref="paper",
        yref="paper",
        y=-0.14,
    )
    watermark(fig)

    return fig
示例#4
0
def fig_b004():
    df = pd.read_csv("https://docs.google.com/spreadsheets/d/"
                     "1VwmTC47fQdnuVFizvI7eTs3xPPFtJwU4/export?format=csv&"
                     "id=1VwmTC47fQdnuVFizvI7eTs3xPPFtJwU4&gid=831947660")

    fig = go.Figure()

    fig.add_traces([
        go.Scatter(
            x=df["Anno"],
            y=df["Fondo Sanitario Nazionale (2008 =100)"].round(1),
            name="Fondo Sanitario Nazionale (2008=100)",
            mode="lines+markers",
            line=dict(width=1.0),
            # marker=dict(symbol=134)
        ),
        go.Scatter(
            x=df["Anno"],
            y=df["Indice prezzi sanità 2008=100"].round(1),
            name="Indice Prezzi Sanità (2008=100)",
            mode="lines+markers",
            line=dict(width=1.0),
            # marker=dict(symbol=134)
        ),
        go.Scatter(
            x=df["Anno"],
            y=df["migrazione sanitaria 2008=100"].round(1),
            name="Migrazione Sanitaria (2008=100)",
            mode="lines+markers",
            line=dict(width=1.0),
            # marker=dict(symbol=134)
        ),
    ])
    w = 500
    h = 400
    lm = 40
    rm = 40
    bm = 120
    tm = 80
    fig.update_layout(
        title=dict(
            text="<b>Fondi per la Sanità, Prezzi e Migrazione Sanitaria</b>"
            '<br><span style="font-size: 12;">Andamento negli anni '
            "(standardizzato, 2008=1)</span>",
            x=0.5,
        ),
        template="plotly_white",
        legend=dict(
            orientation="h",
            x=0.5,
            y=-70 / (h + bm + tm),
            yanchor="top",
            xanchor="center",
        ),
        width=w,
        height=h,
        margin={
            "l": lm,
            "r": rm,
            "b": bm,
            "t": tm,
            "autoexpand": False,
        },
    )
    fig.add_annotation(
        text="Fonti: Eurostat, Ministero della Sanità, "
        "Elaborazioni su dati Ilsole24Ore/Conferenza Stato-Regioni",
        xref="paper",
        yref="paper",
        yanchor="bottom",
        font=dict(size=9, color="grey"),
        y=-340 / (h + bm + tm),
        showarrow=False,
    )

    watermark(fig, annot_y=-270 / (h + bm + tm), logo_y=-235 / (h + bm + tm))

    return fig
示例#5
0
def fig_c001(y="test_pthab", regions=["Lombardia", "Veneto"]):
    data = get_pop_covid_regions()
    covid_lomb_ven = data[data.region.isin(regions)]
    ita_mean = data.groupby("time", as_index=False).mean()

    fig = px.line(
        map_names(covid_lomb_ven),
        x=map_names("time"),
        y=map_names(y),
        color=map_names("region"),
        template="plotly_white",
        labels=labels,
        width=600,
        height=450,
    )

    fig.update_traces(
        mode="lines",
        line=dict(width=1.0),
        marker=dict(symbol=134),
    )

    fig.add_trace(
        go.Scatter(
            x=ita_mean["time"],
            y=ita_mean[y],
            line=dict(dash="dot", color="firebrick"),
            mode="lines",
            name="Media ITA",
        ), )

    for trace in fig.data:
        fig.add_trace(
            go.Scatter(
                x=trace["x"][[-1]],
                y=trace["y"][[-1]],
                text=trace["name"],
                textposition="middle right",
                marker=dict(color=trace["line"]["color"]),
                mode="markers+text",
                name=trace["name"],
                showlegend=False,
            ))

    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.1,
        yanchor="top",
    )

    fig.update_layout(
        title=dict(
            text=f"<b>{labels[y]}: Lombardia e Veneto</b>",
            x=0.5,
        ),
        xaxis=dict(
            range=[
                data["time"].min(),
                data["time"].max() + pd.to_timedelta(10, "d"),
            ],
            title=None,
        ),
        margin={
            "l": 60,
            "r": 30,
            "t": 100,
            "b": 100,
            "autoexpand": False
        },
        legend=dict(
            orientation="h",
            title=None,
            xanchor="center",
            x=0.5,
            y=-0.15,
            yanchor="top",
        ),
        dragmode=False,
    )

    watermark(fig)

    return fig
示例#6
0
def plot(df,
         x,
         y,
         pl_kwargs,
         labels,
         title,
         update_layout_kwargs,
         line_shape=None):
    fig = px.line(df,
                  x=x,
                  y=y,
                  color="geo",
                  template="plotly_white",
                  title=title,
                  labels=labels,
                  line_shape=line_shape,
                  **pl_kwargs)

    for n, trace in enumerate(fig.select_traces()):
        trace["line"]["width"] = 0.75
        trace["mode"] = "lines+markers"
        trace["marker"] = {"symbol": 133, "opacity": 0.5, "size": 3}

        trace = go.Scatter(
            x=trace["x"][-1:],
            y=trace["y"][-1:],
            name=trace["name"],
            text=[trace["name"]],
            showlegend=False,
            mode="markers",
            textposition="middle right",
            marker=dict(color=trace["line"]["color"]),
        )

        if trace["name"] in [
                "Italy",
                "South Korea",
                "China",
                "Canada",
                "Australia",
                "United States",
                "Germany",
                "United Kingdom",
                "Spain",
        ]:
            trace["mode"] = "markers+text"
        fig.add_trace(trace)

    update_kwa = dict(
        width=400,
        margin={
            "r": 20,
            "b": 180,
            "t": 80,
            "l": 70,
            "autoexpand": False
        },
        height=750,
        title={"x": 0.5},
        showlegend=False,
        legend=dict(orientation="v", x=0.0, y=1.0, title=None),
        xaxis=dict(
            rangeslider=dict(visible=True),
            type="date" if x == "time" else "linear",
        ),
    )
    update_kwa.update(update_layout_kwargs)

    fig.update_layout(**update_kwa)

    return watermark(fig)
示例#7
0
def fig_a005():
    medici_df = pd.read_csv(
        "https://docs.google.com/spreadsheets/d/e/"
        "2PACX-1vRNSiOhlGO4r2Dh2cSr2zJbQ-iUfqqbQojs"
        "aTe4z1omzhuIjI_fzJCoD3EFNzgCeXMeX-3cVsZK1hZS/pub?output=csv"
    )
    medici_df = medici_df.query("Anno == 2017")
    medici_df = medici_df.dropna(subset=["Regione"])
    medici_df = medici_df.replace("Emilia_Romagna", "Emilia-Romagna")
    medici_df = medici_df.replace("Friuli_Ven_Giu", "Friuli-Venezia Giulia")
    medici_df = medici_df.replace("PA_bolzano", "P.A. Bolzano")
    medici_df = medici_df.replace("PA_trento", "P.A. Trento")
    medici_df = medici_df[medici_df.Regione != ""]
    medici_df.loc[
        medici_df.Adempiente.isna() | (medici_df.Adempiente == ""),
        "Adempiente",
    ] = "Non Sottoposta a Verifica"

    fig_a005 = px.bar(
        medici_df,
        x="Regione",
        y="LEA",
        # hover_data=["Adempiente"],
        color="Adempiente",  # subset.time.astype(str),
        color_discrete_map={
            "Non Sottoposta a Verifica": "#BAB0AC",
            "Non Adempiente": "#E45756",
            "Adempiente": "#54A24B",
        },
        # range_y=(0, 1060),
        width=650,
        height=400,
        # barmode="group",
        template="plotly_white",
        labels={"LEA": "Punteggio LEA"},
        color_discrete_sequence=px.colors.qualitative.Dark24,
        title="<br><b>Punteggi LEA (Livelli Essenziali di Assistenza)</b></br>"
        '<span style="font-size: 12px;">Anno 2017</span>',
    )
    fig_a005.add_shape(
        # Line Vertical
        dict(
            type="line",
            x0=-1.0,
            y0=160,
            x1=21.0,
            y1=160,
            line=dict(
                color="#D45113",
                width=1,
                # dash="dot",
            ),
            opacity=1.0,
        )
    )
    fig_a005.update_layout(
        margin={"l": 50, "r": 20, "t": 80, "b": 170, "autoexpand": False},
        legend=dict(orientation="h", y=-0.78, title=None),
        xaxis=dict(title=None),
        title=dict(x=0.5, y=0.96),
    )
    fig_a005.add_annotation(
        text="Fonte: Rielaborazione BuildNN & Tortuga da Ministero della "
        "Salute",
        font=dict(size=9, color="grey"),
        showarrow=False,
        xref="paper",
        yref="paper",
        y=-1.04,
    )
    fig_a005.add_annotation(
        x=-0.5,
        y=160,
        xref="x",
        yref="y",
        xanchor="left",
        yanchor="middle",
        text="<b>Livello Minimo</b>",
        showarrow=False,
        font=dict(family="Courier New, monospace", size=10, color="#ffffff"),
        align="left",
        bordercolor="#c7c7c7",
        borderwidth=0,
        borderpad=0,
        bgcolor="#D45113",
        # opacity=0.75
    )

    watermark(fig_a005)
    return fig_a005
示例#8
0
def fig_a004():

    es_unit_value_map, es_geo_value_map = get_es_maps()
    es_isco08_value_map = dict(prep_eurostat.var["eurostat"]["isco08"])

    hlth_rs_prsrg = prep_eurostat.parse_eurostat_dataset("hlth_rs_prsrg")
    hlth_rs_prsrg = hlth_rs_prsrg.query("unit == 'P_HTHAB'").drop(
        columns=["unit"]
    )

    # curative_beds = hlth_rs_prsrg.query("facility == 'HBEDT_CUR'").drop(
    #     columns=["facility"]
    # )
    hsp_pers = hlth_rs_prsrg.loc[
        hlth_rs_prsrg["geo"].str.startswith("IT")
        | hlth_rs_prsrg["geo"].isin(["DE", "FR"])
    ]

    with warnings.catch_warnings(record=True):

        hsp_pers["time"] = hsp_pers["time"].dt.year
        hsp_pers["isco08"] = hsp_pers["isco08"].replace(es_isco08_value_map)
        hsp_pers["Regione"] = hsp_pers["geo"].replace(es_geo_value_map)

    # --- CHARTS ---
    field = "isco08"
    cls = "Nurses and midwives"
    subset = hsp_pers.query("time == 2008 | time == 2016")
    subset = (
        subset[subset[field] == cls]
        .rename(columns={"value": cls})
        .drop(columns=[field])
    )
    subset["time"] = subset["time"].astype(str)

    subset["level"] = subset["geo"].apply(len)
    subset = subset.sort_values(by=["time", "level"])

    fig_a004 = px.bar(
        subset,
        x="Regione",
        y=cls,
        hover_data=["geo"],
        color="time",
        category_orders={0: "2008", 1: "2016"},
        range_y=(0, 1060),
        width=500,
        height=400,
        barmode="group",
        template="plotly_white",
        labels={cls: "Personale per 100.000 ab."},
        color_discrete_sequence=px.colors.qualitative.Dark24,
        title="<br><b>Personale Infermieristico e Ostetrico</b></br>"
        '<span style="font-size: 12px;">Unità di Personale '
        "per 100.000 abitanti: Confronto 2008 vs. 2016</span>",
    )
    fig_a004.add_shape(
        # Line Vertical
        dict(
            type="line",
            x0=2.5,
            y0=-10,
            x1=2.5,
            y1=900,
            line=dict(
                color="grey",
                width=1,
                # dash="dot",
            ),
            opacity=0.5,
        )
    )
    fig_a004.update_layout(
        margin={"l": 50, "r": 20, "t": 80, "b": 150, "autoexpand": False},
        legend=dict(orientation="h", y=-0.58, title=None),
        xaxis=dict(title=None),
        title=dict(x=0.5, y=0.96),
        annotations=[
            dict(
                text="Fonte: Rielaborazione BuildNN & Tortuga da Eurostat",
                font=dict(size=9, color="grey"),
                showarrow=False,
                xref="paper",
                yref="paper",
                y=-0.84,
            )
        ],
    )
    watermark(fig_a004, logo_y=-.75, annot_y=-.82)

    return fig_a004
示例#9
0
def fig_a001():

    es_unit_value_map, es_geo_value_map = get_es_maps()
    es_facility_value_map = dict(prep_eurostat.var["eurostat"]["facility"])

    hlth_rs_bdsrg = prep_eurostat.parse_eurostat_dataset("hlth_rs_bdsrg")
    hlth_rs_bdsrg = hlth_rs_bdsrg.query("unit == 'P_HTHAB'").drop(
        columns=["unit"]
    )

    # curative_beds = hlth_rs_bdsrg.query("facility == 'HBEDT_CUR'").drop(
    #     columns=["facility"]
    # )
    hsp_beds = hlth_rs_bdsrg.loc[
        hlth_rs_bdsrg["geo"].str.startswith("IT")
        | hlth_rs_bdsrg["geo"].isin(["DE", "FR"])
    ]

    with warnings.catch_warnings(record=True):
        hsp_beds["time"] = hsp_beds["time"].dt.year
        hsp_beds["facility"] = hsp_beds["facility"].replace(
            es_facility_value_map
        )
        hsp_beds["Regione"] = hsp_beds["geo"].replace(es_geo_value_map)

    # --- CHARTS ---
    subset = hsp_beds.query("time == 2001 | time == 2017")
    subset = subset[subset.facility.str.startswith("Avail")]
    subset["time"] = subset["time"].astype(str)

    subset["level"] = subset["geo"].apply(len)
    subset = subset.sort_values(by=["time", "level"])

    fig_a001 = px.bar(
        subset,
        x="Regione",
        y="value",
        hover_data=["geo"],
        color="time",
        category_orders={0: "2017", 1: "2001"},
        width=500,
        height=400,
        barmode="group",
        template="plotly_white",
        labels={"value": "Totale Posti Letto per 100.000 ab."},
        color_discrete_sequence=px.colors.qualitative.Dark24,
        title="<br><b>Totale Posti Letto nelle Strutture Ospedaliere</b></br>"
        '<span style="font-size: 12px;">Posti Letto '
        "per 100.000 abitanti: Confronto 2001 vs. 2017</span>",
    )
    fig_a001.add_shape(
        # Line Vertical
        dict(
            type="line",
            x0=2.5,
            y0=-10,
            x1=2.5,
            y1=900,
            line=dict(
                color="grey",
                width=1,
                # dash="dot",
            ),
            opacity=0.5,
        )
    )
    fig_a001.update_layout(
        margin={"l": 50, "r": 20, "t": 80, "b": 150, "autoexpand": False},
        legend=dict(orientation="h", y=-0.58, title=None),
        xaxis=dict(title=None),
        title=dict(x=0.5, y=0.96),
        annotations=[
            dict(
                text="Fonte: Rielaborazione BuildNN & Tortuga da Eurostat",
                font=dict(size=9, color="grey"),
                showarrow=False,
                xref="paper",
                yref="paper",
                y=-0.84,
            )
        ],
    )
    watermark(fig_a001, logo_y=-.75, annot_y=-.82)

    return fig_a001
示例#10
0
def fig_a002():

    # -- PHARMA
    pharma = (
        prep_salutegov.parse_dataset("pharmacies")
        .groupby("region_code")[["pharmacy_code"]]
        .nunique()
        .reset_index()
        .rename(columns={"pharmacy_code": "n_pharmacies"})
    )
    asl = (
        prep_salutegov.parse_dataset("asl_comuni_pop")
        .replace("", np.nan)
        .dropna(subset=["region_code"])
    )
    asl["TOTALE"] = (
        asl["TOTALE"]
        .str.replace(".", "")
        .str.replace(",", ".")
        .replace("", np.nan)
        .astype(float)
    )
    pop = asl.groupby(["region_code"]).agg(
        population=pd.NamedAgg("TOTALE", "sum"),
        region=pd.NamedAgg("region", "first"),
    )

    pharma["population"] = pop.reindex(pharma["region_code"].values)[
        "population"
    ].values
    pharma["region"] = (
        pop.reindex(pharma["region_code"].values)["region"].str.title().values
    )
    pharma.loc[
        pharma.region_code == "04", "region"
    ] = "Trentino-Alto Adige/Südtirol"
    pharma["hab_per_pharma"] = (
        (pharma["population"] / pharma["n_pharmacies"]).round(0).astype(int)
    )

    fig_a002 = px.choropleth(
        pharma,
        geojson=GDF_REG,
        color="hab_per_pharma",
        hover_data=["region", "n_pharmacies", "population"],
        locations="region_code",
        # range_color=(0, 3.5),
        center={"lat": 42.65, "lon": 12.4},
        featureidkey="properties.reg_istat_code",
        projection="mercator",
        template="plotly_white",
        color_continuous_scale=px.colors.diverging.Temps,
        labels={
            "region_code": "Cod. Regione",
            "region": "Regione",
            "hab_per_pharma": "Ab. per Farmacia",
            "n_pharmacies": "Numero Farmacie",
            "population": "Numero Abitanti",
        },
        # line_shape="spline",
    )
    fig_a002.update_geos(fitbounds="locations", visible=False).update_layout(
        width=600, height=600
    )

    fig_a002.update_layout(
        margin={"l": 80, "r": 140, "b": 80, "t": 100, "autoexpand": False},
        title=dict(
            text="<br><b>Abitanti per Farmacia</b></br>"
            '<span style="font-size: 11px;">Anno 2018 - Meno è Meglio</span>',
            x=0.5,
            y=0.96,
        ),
        xaxis=dict(title=None),
        yaxis_tickformat="20",
        legend=dict(orientation="h", yanchor="top", y=-0.15, title=None),
        # showlegend=False,
        annotations=[
            dict(
                text="Fonte: Rielaborazione BuildNN & Tortuga da Ministero "
                "della Salute",
                font=dict(size=9, color="grey"),
                showarrow=False,
                xref="paper",
                yref="paper",
                y=-0.0,
            )
        ],
    )

    watermark(fig_a002)

    return fig_a002
示例#11
0
def fig_e001():
    regioni = prep_dpc_regions()
    id_vars = [
        "time",
        "country",
        "region_code",
        "region",
        "latitude",
        "longitude",
        "epidemic_start",
        "epidemic_age",
    ]
    value_vars = [
        "n_hospitalized",
        "n_intensive_care",
        # 'n_home_quarantine',
        #  'being_tested',
        "new_deceased",
        "new_discharged",
    ]
    hosp_melted = regioni.melt(id_vars=id_vars, value_vars=value_vars)
    hosp_melted

    f1 = (
        px.area(
            hosp_melted[
                hosp_melted.region.isin(["Lombardia", "Veneto"])
            ].replace(
                {
                    "n_hospitalized": "Ospedalizzati (no T.I.)",
                    "n_intensive_care": "Terapia Intensiva",
                    # 'n_home_quarantine',
                    # 'being_tested',
                    "new_deceased": "Decessi",
                    "new_discharged": "Dimessi/Guariti",
                }
            ),
            labels={"value": "Valore", "time": "Dara", "region": "Regione"},
            x="time",
            y="value",
            color="variable",
            color_discrete_sequence=px.colors.qualitative.T10,
            facet_col="region",
            template="plotly_white",
            title="<b>Tamponi vs Impatto COVID-19 sugli Ospedali</b><br>"
            '<span style="font-size: 12px;">Confronto tra Veneto e Lombardia'
            "</span>",
        )
        .update_layout(
            margin={"t": 100, "autoexpand": False},
            title=dict(y=0.92, x=0.5),
            width=820,
            height=450,
            yaxis=dict(title=None, tickformat="d"),
            legend=dict(orientation="h", title=None, y=-0.13),
            dragmode=False,
        )
        .update_xaxes(title=None)
    )

    f2 = px.bar(
        regioni[regioni.region.isin(["Lombardia", "Veneto"])],
        x="time",
        y="being_tested",
        color_discrete_sequence=["steelblue"],
        facet_col="region",
        opacity=0.5,
    ).update_traces(hoverinfo="skip").update_layout(dragmode=False)

    for n, trace in enumerate(f2.select_traces()):
        trace["name"] = "Tamponi Effettuati"
        if n == 0:
            trace["showlegend"] = True
        f1.add_trace(trace, 1, n + 1)

    f1.add_annotation(
        text="Fonte: Dipartimento di Protezione Civile",
        font=dict(size=9, color="grey"),
        showarrow=False,
        xref="paper",
        yref="paper",
        y=-0.28,
    )

    watermark(f1)

    return f1
示例#12
0
def bar_line_plot(
    df,
    x="date_report",
    bary=[  # col_name, label, color, trace_kwargs
        ("new_positives", "Nuovi Casi", "#FF8A5B", {}),
        ("new_deaths", "Decessi", "#EA526F", {}),
        ("new_discharged", "Dimessi/Guariti", "#25CED1", {}),
    ],
    barmode="stack",
    liney=(
        "being_tested",
        "Test Effettuati",
        "firebrick",
        {"mode": "lines+markers"},
    ),
    yscale=100,
    secondaryy=False,
    y1_title="<b>N. Casi -- N. Test Effettuati/100</b>",
    y2_title="<b>N. Test Effettuati</b>",
    title="<br><b>Andamento del Contagio in Korea del Sud</b></br>"
    '<span style="font-size: 13px;">'
    " Casi Attivi, Dimessi/Guariti, Decessi e Test Effettuati</span>",
    fonte="Fonte: Korea Centers for Desease Control and Prevention",
):

    fig = make_subplots(specs=[[{"secondary_y": secondaryy}]])

    for col_name, label, color, trace_kwargs in bary:
        trace = (
            go.Bar(
                x=df[x],
                y=df[col_name],
                name=label,
                marker=dict(color=color),
                opacity=0.75,
                **trace_kwargs
            ),
        )
        fig.add_trace(trace[0], secondary_y=False)

    fig.update_layout(barmode=barmode)

    # -- TESTS
    col_name, label, color, trace_kwargs = liney
    line_trace = go.Scatter(
        x=df[x],
        y=df[col_name] / yscale,
        name=label,
        line=dict(color=color, width=0.75,),
        marker=dict(symbol=134),
        **trace_kwargs
    )
    fig.add_trace(line_trace, secondary_y=secondaryy)

    if secondaryy:
        fig.update_yaxes(
            title=dict(text=y2_title, font=dict(size=11)),
            range=(0, (df[liney[0]] / yscale).max() * 1.1),
            secondary_y=True,
            showgrid=False,
        )

    fig.update_yaxes(
        title=dict(text=y1_title, font=dict(size=11)), secondary_y=False
    )

    fig.update_layout(
        margin={"t": 80, "l": 40, "r": 20, "autoexpand": False},
        title=dict(text=title, x=0.5,),
        template="plotly_white",
        width=750,
        height=500,
        legend=dict(orientation="h"),
        annotations=[
            dict(
                text=fonte,
                font=dict(size=9, color="grey"),
                showarrow=False,
                xref="paper",
                yref="paper",
                y=-0.24,
            )
        ],
    )

    watermark(fig)

    return fig
示例#13
0
def line_double_trace(
    elements,
    secondary_elements=None,
    main_line_mode="lines+markers+text",
    secondary_line_dash="solid",
    main_line_width=1.75,
    secondary_line_width=0.75,
    label_format="<b>{:.0f}</b>",
    label_each=3,
    primary_y_title="<b>Numero Tamponi Eseguiti</b>",
    secondary_y_title="<b>Nuovi Casi Positivi</b>",
    title="<br><b>Numero di Tamponi Eseguiti vs Nuovi Casi COVID-19</b></br>"
    '<span style="font-size: 12;">Differenza tra italia e Korea del '
    "Sud</span>",
    xaxis_title="N. Giorni Trascorsi dal 100° Caso Ufficiale",
    source="Fonte: Dipartimento di Protezione Civile Italiana, "
    "Korea Centers for Desease Control and Prevention</p>",
    source_y=-0.49,
    primary_y_kwargs={},
    secondary_y_kwargs={},
    layout_kwargs={},
):
    """
    elements = [(x: array, y: array, name: str, color: str, textcolor: str)]
    secondary_elements = [(x: array, y: array, name: str, color: str)]
    """

    fig = make_subplots(
        specs=[[{"secondary_y": True if secondary_elements else False}]]
    )

    for x, y, name, color, textcolor in elements:
        fig.add_trace(
            go.Scatter(
                x=x,
                y=y,
                text=[
                    label_format.format(x) if n % label_each == 0 else ""
                    for n, x in enumerate(y)
                ],
                name=name,
                # --- LINE
                textposition="top center",
                textfont=dict(color=textcolor),
                line=dict(color=color, width=main_line_width,),
                mode=main_line_mode,
                marker=dict(color=color),
                line_shape="spline",
                # ---
                opacity=0.75,
                showlegend=True,
            )
        )

    if secondary_elements:
        for x, y, name, color in secondary_elements:
            fig.add_trace(
                go.Scatter(
                    x=x,
                    y=y,
                    name=name,
                    # --- LINE
                    line=dict(
                        color=color,
                        width=secondary_line_width,
                        dash=secondary_line_dash,
                    ),
                    mode="lines",
                    line_shape="spline",
                    # ---
                    opacity=0.75,
                    showlegend=True,
                ),
                secondary_y=True,
            )

    # Primary
    fig.update_yaxes(
        title=dict(text=primary_y_title, font=dict(size=11)),
        secondary_y=False,
        **primary_y_kwargs
    )

    # Secondary
    fig.update_yaxes(
        title=dict(text=secondary_y_title, font=dict(size=11)),
        secondary_y=True,
        showgrid=False,
        **secondary_y_kwargs
    )

    _layout_kwargs_std = dict(
        title=dict(text=title, x=0.5, y=0.98),
        margin={"l": 40, "r": 10, "t": 80, "b": 140, "autoexpand": False},
        template="plotly_white",
        width=700,
        height=450,
        showlegend=True,
        legend=dict(orientation="h", y=-0.22, x=0.5, xanchor="center"),
        # yaxis=dict(range=(0, 400)),
        xaxis=dict(title=xaxis_title),
        annotations=[
            dict(
                font=dict(size=9, color="grey"),
                showarrow=False,
                yref="paper",
                xref="paper",
                text=source,
                y=source_y,
            )
        ],
    )
    _layout_kwargs_std.update(layout_kwargs)

    fig.update_layout(**_layout_kwargs_std)
    watermark(fig)

    return fig
示例#14
0
         yaxis={"title": None},
         annotations=[
             dict(
                 text=
                 "Fonte: Fonte: Open Data Ministero dell'Economia e Finanze.",
                 showarrow=False,
                 yref="paper",
                 y=mb * 0.9,
                 font={
                     "color": "grey",
                     "size": 9
                 },
             )
         ],
     )
     watermark(f).show()
 bilancio_data = bilancio.loc[bilancio["Descrizione Programma"].isin(
     programmi + p2)]
 fig = make_subplots(
     rows=2,
     cols=1,
     # shared_xaxes=True,
     row_heights=[800, 1250],
     column_widths=[450],
     vertical_spacing=0.03,
     specs=[[{
         "type": "table"
     }], [{
         "type": "sunburst"
     }]],
 )