Ejemplo n.º 1
0
    def get_chart(self, df, gj):
        fig = px.choropleth_mapbox(df,
                                   title="<b>Somministrazioni prima dose</b>",
                                   geojson=gj, color="percentuale1dose",
                                   locations=df.regione, featureidkey="properties.reg_name",
                                   center={"lat": 41.902782, "lon": 12.496366},
                                   mapbox_style="open-street-map", zoom=4.35,
                                   color_continuous_scale="Viridis",
                                   opacity=0.7)
        fig.update_layout(margin={"r": 0, "t": 25, "l": 0, "b": 0})
        fig.update_layout(title_x=0.5)

        fig2 = px.choropleth_mapbox(df,
                                    title="<b>Somministrazioni seconda dose</b>",
                                    geojson=gj, color="percentuale2dose",
                                    locations=df.regione, featureidkey="properties.reg_name",
                                    center={"lat": 41.902782, "lon": 12.496366},
                                    mapbox_style="open-street-map", zoom=4.35,
                                    color_continuous_scale="Viridis",
                                    opacity=0.7)
        fig2.update_layout(margin={"r": 0, "t": 25, "l": 0, "b": 0})
        fig2.update_layout(title_x=0.5)
        fig.update_layout(coloraxis_showscale=False)
        fig2.update_layout(coloraxis_showscale=False)

        return fig, fig2
Ejemplo n.º 2
0
def create_map(incremental, metric, n_clicks, map_data, state_filter):
    try:
        state_filter = int(json.loads(state_filter)['points'][0]['pointIndex'])
    except TypeError:
        state_filter = "Countrywide"

    if metric == "% Positive":
        col_to_plot = "%Positive"
        colors = "Purpor"
        format_type = ":.1f%"
    elif metric == "Confirmed Cases":
        col_to_plot="Cases"
        colors="Greens"
        format_type = ":,.0f"
    else:
        col_to_plot = "Deaths"
        colors = "Blues"
        format_type = ":,.0f"

    map_data = pd.read_json(json.loads(map_data))

    df_to_plot = map_data[map_data["Incremental"]==incremental]
    df_to_plot['color_field'] = df_to_plot[col_to_plot]/max(df_to_plot[col_to_plot])

    if metric == "% Positive":
        fig = px.choropleth_mapbox(df_to_plot, geojson=states, locations='id', color='color_field',
                                   color_continuous_scale=colors,
                                   range_color=(0, 0.5),
                                   mapbox_style="carto-positron",
                                   zoom=2.5, center = {"lat": 37.0902, "lon": -95.7129},
                                   opacity=0.5,
                                   hover_data={'State':True,
                                               'id':False,
                                               'color_field':False,
                                                col_to_plot:format_type})
    else:
        fig = px.choropleth_mapbox(df_to_plot, geojson=states, locations='id', color='color_field',
                                   color_continuous_scale=colors,
                                   #range_color=(0, 40),
                                   mapbox_style="carto-positron",
                                   zoom=2.5, center = {"lat": 37.0902, "lon": -95.7129},
                                   opacity=0.5,
                                   hover_data={'State':True,
                                               'id':False,
                                               'color_field':False,
                                                col_to_plot:format_type}
                                  )



    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},
                      coloraxis_showscale=False)
    fig.update_layout(clickmode='event+select')
    if dash.callback_context.triggered[0]['prop_id'].split('.')[0] != 'clear-geo':
        fig = add_selected_data(fig, state_filter)

    return(fig)
Ejemplo n.º 3
0
def draw_map(sample_data, odm_instance, geo):
    map_height = 800
    if geo is None:
        return px.choropleth_mapbox()
    map_center = visualization_helpers.get_map_center(geo)
    zoom_level = visualization_helpers.get_zoom_level(geo, map_height)
    sample_data["Polygon.name"] = poly_name_from_agg(odm_instance, sample_data)
    sample_data["Site.icon"] = sample_data["Site.type"].apply(
        lambda x: site_icons.get(x, "marker"))
    site_data = sample_data[[
        "Site.name", "Site.type", "Site.geoLat", "Site.geoLong", "Site.icon"
    ]].drop_duplicates()
    # print(site_data["Site.icon"].to_list())
    # Choropleth layer for sewersheds
    fig = px.choropleth_mapbox(
        sample_data,
        geojson=geo,
        locations="Site.polygonID",
        featureidkey="properties.polygonID",
        custom_data=["Polygon.name"],
        hover_name="Polygon.name",
        color="Polygon.name",
        center=map_center,
        opacity=0.5,
        mapbox_style="open-street-map",
        zoom=zoom_level,
    )
    fig.add_scattermapbox(
        below="",
        name="Sampling Sites",
        lat=site_data["Site.geoLat"],
        lon=site_data["Site.geoLong"],
        customdata=site_data["Site.name"],
        mode="markers",
        marker=dict(
            size=20,
            symbol="circle",
            color="black",
            opacity=1,
        ),
        hoverinfo="text",
        text=site_data["Site.name"],
        showlegend=True,
    )
    fig.update_layout(clickmode="event+select",
                      height=map_height,
                      legend_orientation="h",
                      legend_yanchor="top",
                      legend_xanchor="left")
    return fig
Ejemplo n.º 4
0
def create_zipcode_geomap(covid_df,
                          zipcode_trip_df,
                          geo_json,
                          covid_attr,
                          zipcode_attr,
                          zoom=9,
                          center={
                              "lat": 40.7,
                              "lon": -73.99
                          }):
    covid_fig = px.choropleth_mapbox(
        covid_df,
        geojson=geo_json,
        color=covid_attr,
        locations="zipcode",
        featureidkey="properties.postalCode",
        mapbox_style="carto-positron",
        hover_data=[
            'neighborhood', 'population', 'median_household_income', 'zipcode',
            'num_tests'
        ],
        zoom=zoom,
        center=center,
        opacity=0.5,
        color_continuous_scale=px.colors.sequential.Reds,
        title="COVID-19 Data",
        width=730,
        height=600)
    zipcode_trip_fig = px.choropleth_mapbox(
        zipcode_trip_df,
        geojson=geo_json,
        color=zipcode_attr,
        locations="zipcode",
        featureidkey="properties.postalCode",
        mapbox_style="carto-positron",
        hover_data=[
            'num_cash_payment', 'num_card_payment', 'num_dropoff',
            'avg_trip_passenger', 'avg_trip_speed_mph', 'avg_trip_distance',
            'avg_total_price', 'avg_price_per_mile'
        ],
        zoom=zoom,
        center=center,
        opacity=0.5,
        color_continuous_scale=px.colors.sequential.Reds,
        title="NYC Yellow Taxi Data",
        width=730,
        height=600)
    return covid_fig, zipcode_trip_fig
Ejemplo n.º 5
0
def update_map2p(dep_select_value):
    df_map2a = df_map2[df_map2['nombre_dep']==dep_select_value]
    coords_dep_f = coords_dep[coords_dep['nombre_dep']==dep_select_value].reset_index()
    map2 = px.choropleth_mapbox(df_map2a,
                           geojson=municipios,
                           color="Conteo",
                           color_continuous_scale="brwnyl",
                           locations="codigo_mun", 
                           featureidkey="properties.MPIO_CCNCT",
                           mapbox_style="carto-positron", 
                           zoom=7,
                           center={"lat": coords_dep_f.latitud[0], "lon": coords_dep_f.longitud[0]},
                           hover_name="nombre_mun",
                           hover_data={"codigo_dep": False,
                                       "codigo_mun": False},
                           labels={"Conteo": "Número de <br> sentencias"})
    map2.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
    map2.update_layout(
            autosize=True,
            hoverlabel=dict(
                    bgcolor="#EDEAE8",
                    font_size=16,
                    font_color = '#1B1B1B')
                    )
    return [
            dcc.Graph( figure = map2 )
    ]
Ejemplo n.º 6
0
def update_choropleth(df, geojson):
    # Prepare the datasets
    primary_df = dp.load_primary_energy_sources(df)
    primary_df = dp.data_subset(primary_df, states=[state for state in primary_df["State"].unique(
    ) if state != "United States"], sectors=["Total"])
    primary_df["BTU"] = primary_df["BTU"]/1_000_000
    primary_df = primary_df.rename(columns={"BTU": "Quadrillion BTU"})
    primary_df = primary_df.groupby(["State", "Year"], as_index=False).sum()
    primary_df = primary_df[primary_df["Year"] == 2018]

    per_cap_df = dp.data_subset(df, states=[state for state in df["State"].unique(
    ) if state != "United States"], sources=["Total"], sectors=["Total consumption per capita"])
    per_cap_df = per_cap_df.rename(columns={"BTU": "Million BTU per capita"})

    max_y = per_cap_df["Million BTU per capita"].max()

    fig = px.choropleth_mapbox(
                            per_cap_df,
                            geojson=geojson,
                            locations="State",
                            color="Million BTU per capita",
                            featureidkey="properties.NAME",
                            color_continuous_scale=plotly.colors.diverging.Temps,
                            range_color=(0, max_y),
                            animation_frame="Year",
    )
    fig.update_layout(
                mapbox_style="carto-positron",
                mapbox_zoom=2.2,
                mapbox_center={"lat": 37.8, "lon": -95.7},
    )
    fig.update_layout(plotting.CHOROPLETH_COLORS)
    # fig.update_layout(plotting.CHOROPLETH_COLORS)
    return fig
    def _update_map_rating_heat_map(self, trigger):
        with open("assets/us-states.json") as geojson:
            states = json.load(geojson)

        df = self._data_handler.get_data_frame_original
        df = df[["state_name",
                 "student_star"]].groupby("state_name").mean().reset_index()

        fig = px.choropleth_mapbox(df,
                                   geojson=states,
                                   locations="state_name",
                                   color="student_star",
                                   color_continuous_scale="tealgrn",
                                   range_color=(0, 5),
                                   center={
                                       "lat": 37.0902,
                                       "lon": -95.7129
                                   },
                                   zoom=3,
                                   opacity=0.5)

        fig.update_layout(mapbox=dict(accesstoken=self._mapbox_token,
                                      style=self._mapbox_style),
                          margin=go.layout.Margin(l=0, r=0, t=0, b=0),
                          paper_bgcolor="rgba(0,0,0,0)",
                          plot_bgcolor="rgba(0,0,0,0)")

        return fig
Ejemplo n.º 8
0
def plot_unemploy_choro_county(df, rangesize, datatype):
    fig_map = px.choropleth_mapbox(
        df,
        geojson=counties,
        locations=df.index,
        color=datatype,
        color_continuous_scale="Reds",
        range_color=rangesize,
        mapbox_style="carto-positron",
        zoom=3,
        center={
            "lat": 37.0902,
            "lon": -95.7129
        },
        opacity=0.5,
    )
    fig_map.update_layout(
        title_text='{} by County'.format(datatype),
        margin={
            "r": 10,
            "t": 0,
            "l": 0,
            "b": 0
        },
    )
    return fig_map
def map_communes():
    fig = px.choropleth_mapbox(df_communes_tot,
                               geojson=geojson_communes,
                               locations="NIS5",
                               color='colorbase',
                               color_continuous_scale="deep",
                               range_color=(3, 10),
                               featureidkey="properties.NIS5",
                               center={
                                   "lat": 50.641111,
                                   "lon": 4.668889
                               },
                               hover_name="CASES",
                               hover_data=["name", "CASES", "NIS5"],
                               height=500,
                               mapbox_style="carto-positron",
                               zoom=6)
    fig.update_geos(fitbounds="locations")
    NB_TICKS = 12
    fig.layout.coloraxis.colorbar = dict(
        title=gettext("Number of cases"),
        titleside="right",
        tickmode="array",
        tickvals=list(range(1, NB_TICKS + 1)),
        ticktext=[str(2**i) for i in range(1, NB_TICKS + 1)],
        ticks="outside")
    fig.update_traces(hovertemplate=gettext(
        "<b>%{customdata[0]}</b><br>%{customdata[1]} cases"))
    fig.update_layout(template="plotly_white", margin=dict(l=0, r=0, t=5, b=0))
    return fig
Ejemplo n.º 10
0
def job():
    print("Start job")
    #filedata = 'C:/Users/ale/OneDrive/Ale/COVID/grafici/dpc-covid19-ita-province-latest.csv'
    filedata = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-province/dpc-covid19-ita-province-latest.csv"
    df = pd.read_csv(filedata,
                     dtype={"sigla_provincia": str},
                     error_bad_lines=True)
    fig1 = px.choropleth_mapbox(df,
                                geojson=geo,
                                color="totale_casi",
                                locations="sigla_provincia",
                                featureidkey="properties.prov_acr",
                                center={
                                    "lat": 42.35,
                                    "lon": 12.70
                                },
                                mapbox_style="carto-positron",
                                zoom=5.5,
                                labels={'totale_casi': 'confirmed cases'})
    fig1.update_layout(title_text=tc,
                       margin={
                           "r": 0,
                           "t": 100,
                           "l": 0,
                           "b": 0
                       },
                       autosize=True,
                       width=1000,
                       height=1100)
    #plot(fig1)
    fig1.show()
    plot(fig1, filename='index.html')
Ejemplo n.º 11
0
def plot_sectorcode_values(hdbSeries, customdata = None, hovertemplate = None):
    """
    Plots hdbSeries, which is a pandas Series with values for each sectorcode
    customdata is a 2D array that contains [custom values] for each sectorcode
    hovertemplate formats the output data for display
    """
    shapefile = Path('/home/jovyan/shared-notebooks/notebooks/HDB_analysis/data/processed/sectorcode/sectorcode.shp')
    sgshp = geopandas.read_file(shapefile)
    geojson = json.loads(sgshp.to_json())
    input_df = hdbSeries.reset_index() #move index to a column
    fig = px.choropleth_mapbox(input_df, geojson=geojson,
                                locations='sc',
                                featureidkey="properties.sectorcode",
                                color=hdbSeries.name,
                                mapbox_style='open-street-map',
                                center = {"lat": 1.3521, "lon": 103.8198},
                                opacity = 0.5,
                                zoom = 10,
                                custom_data = ['sc'],
                                height = 600,
                                color_continuous_scale = 'jet',
                                range_color = list(hdbSeries.quantile([.1, 0.9]))
                                )
    if customdata is not None:
        fig.customdata = customdata
    if hovertemplate is None:
        hovertemplate = "<b>Sector Code: %{customdata[0]}</b><br>"+"{}".format(hdbSeries.name)+": %{z}<extra></extra>"
    fig['data'][0].hovertemplate = hovertemplate
    return fig
Ejemplo n.º 12
0
def update_map_plot(crime_drop, year_drop):
    dfmap = dff[(dff['year'] == year_drop) & (dff['crime'].isin(crime_drop))]
    dfmap = dfmap.groupby('mapid').sum().reset_index()
    Map_fig2 = px.choropleth_mapbox(
        dfmap,
        locations='mapid',
        color='total',
        #featureidkey="properties.NOMBRE_DPT",
        geojson=geoj,
        zoom=7,
        mapbox_style="stamen-toner",
        center={
            "lat": 4.655115,
            "lon": -74.055404
        },  #Center
        color_continuous_scale="matter",  #Color Scheme
        opacity=0.5,
        title='Total crimes in Colombia')
    Map_fig2.update_layout(title='Total de Crímenes por Departamento',
                           margin={
                               "r": 0,
                               "t": 0,
                               "l": 0,
                               "b": 0
                           },
                           paper_bgcolor="#F8F9F9")

    return Map_fig2
def update_graph(option_slctd):
    print(option_slctd)
    print(type(option_slctd))

    container = "The year chosen by user was: {}".format(option_slctd)

    dff = suicide.copy()
    dff = dff[dff["Year"] == option_slctd]

    # Plotly Express
    fig = px.choropleth_mapbox(
        dff,
        geojson=counties,
        color="Suicide_Death_Rate",
        locations="FIPS",
        hover_name="County",
        hover_data=["Deaths", "Population", "Suicide_Death_Rate"],
        center={
            "lat": 38.72490,
            "lon": -95.61446
        },
        mapbox_style="carto-positron",
        zoom=3)

    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    #     fig.update_layout(
    #         title_text="Bees Affected by Mites in the USA",
    #         title_xanchor="center",
    #         title_font=dict(size=24),
    #         title_x=0.5,
    #         geo=dict(scope='usa'),
    #     )

    return container, fig
Ejemplo n.º 14
0
def get_provincial_map(df_province, province_map_json, cmap):
    fig = px.choropleth_mapbox(
        data_frame=df_province,
        geojson=province_map_json,
        locations='sigla_provincia',
        featureidkey='properties.prov_acr',
        color='totale_casi',
        color_continuous_scale=cmap,
        range_color=(0, math.ceil(df_province['totale_casi'].max() + 1)),
        hover_data=["growth_rate", "increased_cases"],
        mapbox_style="carto-positron",
        zoom=4,
        center={
            "lat": 42.00107394,
            "lon": 10.3283498
        },
        #opacity=1,
        animation_frame="giorno",
        labels={
            "giorno": "Giorno",
            "totale_casi": "Totale Casi",
            'data': 'Data',
            "growth_rate": "Growth Rate",
            "increased_cases": "Nuovi Casi",
            "increased_tamponi": "Nuovi Tamponi Effettuati",
            "sigla_provincia": "Sigla Provincia"
        },
        height=600,
    )
    return fig
def choropleth_state_v2(df, states_centers, state_name):
    
    lat_lon = states_centers[states_centers['Abbr'] == state_name][['lat', 'lon']]

    center_dict = {'lat': lat_lon['lat'].values[0],'lon': lat_lon['lon'].values[0] }
    zoom_dict =get_zoom_level(df)
    fig = px.choropleth_mapbox(df,
                            geojson=df.geometry,
                            locations=df.index,
                            color='covid_values',
                                center = center_dict,
                            mapbox_style='open-street-map',
                                zoom=zoom_dict[state_name],
                                opacity=0.6, 
                            color_continuous_scale='rainbow'
                            )

    fig.update_geos(fitbounds="locations", visible=False),
    fig.update_traces(marker_line_width=2, marker_line_color='black')
    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},   
                      geo=dict(bgcolor= config['plot_color']),
                      coloraxis_colorbar=dict(title=dict(text="Cumulative cases", font=dict(color='white', size=18)), tickfont=dict(size=14, color='white')))
    fig.update_layout(dict( paper_bgcolor=config['paper_color']))


    return fig
Ejemplo n.º 16
0
def choropleth_country_fig():
    fig = px.choropleth_mapbox(get_country_choropeth_data(),
                               geojson=chile_g_geojson,
                               color_continuous_scale="PiYG_r",
                               color_continuous_midpoint=0.05,
                               locations="Codigo region",
                               color='Positividad',
                               featureidkey="properties.COD_REGI",
                               hover_data={
                                   "Region": True,
                                   "Positividad": ":.1%",
                                   "Codigo region": False
                               },
                               height=800,
                               mapbox_style="carto-positron",
                               zoom=3.4,
                               center={
                                   "lat": -39,
                                   "lon": -70.6653
                               },
                               opacity=0.5)
    # fig.update_geos(fitbounds="locations", visible=False)
    fig.update_layout(coloraxis_showscale=False,
                      margin={
                          "r": 5,
                          "t": 0,
                          "l": 5,
                          "b": 0
                      })
    return fig
Ejemplo n.º 17
0
def choropleth_fig():
    fig = px.choropleth_mapbox(get_rm_choropleth_data(),
                               geojson=communes_g,
                               color_continuous_scale="PiYG_r",
                               color_continuous_midpoint=0.05,
                               locations="Comuna norm",
                               color='Positividad',
                               featureidkey="properties.NOM_COM_NORM",
                               hover_data={
                                   "Comuna": True,
                                   "Positividad": ":.1%",
                                   "Comuna norm": False
                               },
                               mapbox_style="carto-positron",
                               zoom=7.5,
                               center={
                                   "lat": -33.5826900,
                                   "lon": -70.6472400
                               },
                               opacity=0.5)
    fig.update_geos(fitbounds="locations", visible=False)
    fig.update_layout(coloraxis_showscale=False,
                      margin={
                          "r": 5,
                          "t": 0,
                          "l": 5,
                          "b": 0
                      })
    return fig
Ejemplo n.º 18
0
def paintCarTrafficInZBS(stat):
    if not (os.path.exists(
            os.path.join(getRootPath(), 'data/trafico/07-2020_zbsMap.csv'))):
        preprocessCarTrafficInZBS()

    grouped_byzbs_mean = pd.read_csv(
        os.path.join(getRootPath(), 'data/trafico/07-2020_zbsMap.csv'))

    zbs_json = loadZBSJson(
        os.path.join(
            getRootPath(),
            "data/COVID/zonas_basicas_salud/zonas_basicas_salud.json"))

    fig = px.choropleth_mapbox(
        grouped_byzbs_mean,
        geojson=zbs_json,
        featureidkey='properties.codigo_geo',
        locations='index',
        color=stat,
        color_continuous_scale="OrRd",
        mapbox_style="carto-positron",
        hover_data=[stat],
        center={
            "lat": 40.417008,
            "lon": -3.703795
        }
        #labels={'casos_confirmados_ultimos_14dias': 'Casos últimos 14 días'}
    )
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

    return fig
def map_communes_cases_per_week():
    maxv = df5.CASES.max()
    fig = px.choropleth_mapbox(
        df5,
        geojson=geojson_communes,
        locations="NIS5",
        color='CASES',
        color_continuous_scale="magma_r",
        range_color=(0, maxv),
        animation_frame="WEEK",
        animation_group="NIS5",
        featureidkey="properties.NIS5",
        center={
            "lat": 50.641111,
            "lon": 4.668889
        },
        hover_name="CASES",
        hover_data=["CASES_PER_1000HABITANT", "CASES", "name"],
        height=600,
        mapbox_style="carto-positron",
        zoom=6)
    fig.update_geos(fitbounds="locations")
    fig.layout.coloraxis.colorbar.title = gettext("Number of cases per week")
    fig.layout.coloraxis.colorbar.titleside = "right"
    fig.layout.coloraxis.colorbar.ticks = "outside"
    fig.layout.coloraxis.colorbar.tickmode = "array"
    fig.update_traces(hovertemplate=gettext(
        "<b>%{customdata[0]} /1000<br><b>%{customdata[1]} cases <br><b>%{customdata[2]}"
    ))
    fig.update_layout(template="plotly_white", margin=dict(l=0, r=0, t=5, b=0))
    return fig
Ejemplo n.º 20
0
def choroplet_plot(plot_dict, geo_data, geo_df, today=None, delay=2, los=8):
    _, _, _, y_pred, _, _ = plot_dict["icu_occupancy"][delay][los]
    if today is None:
        today = n_obs
    # Index regions `today`
    y_pred = np.array(y_pred)
    geo_df['% additional demand'] = y_pred[[3, 4, 3, 2, 1, 2, 0, 5, 6], today].round(2)

    fig = px.choropleth_mapbox(
        geo_df,
        geojson=geo_data,
        locations='ID',
        color='% additional demand',
        color_continuous_scale="Portland",
        featureidkey="properties.nuts118cd",
        range_color=(0, 100),
        mapbox_style="carto-positron",
        hover_data=["Region", "% additional demand"],
        zoom=4.7,
        center={"lat": 53, "lon": -2},
        opacity=0.7
    )
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

    return fig
Ejemplo n.º 21
0
def map_cases_incidence_provinces():
    div = 250
    fig = px.choropleth_mapbox(
        df3d,
        geojson=geojson_provinces,
        locations="PROV",
        color='CASES_PER_100KHABITANT',
        range_color=(0, 300),
        color_continuous_scale="magma_r",
        #color_continuous_scale=[(0, "green"), (15/150, "green"), (15/150, "yellow"),
        #                        (30/150, "yellow"), (30/150, "orange"), (50/150, "orange"),
        #                        (50/150, "red"), (100/150, "red"),(100/150, "black"),(150/150, "black")],
        featureidkey="properties.proviso",
        center={
            "lat": 50.641111,
            "lon": 4.668889
        },
        hover_name="CASES_PER_100KHABITANT",
        hover_data=["CASES_PER_100KHABITANT", "POP", "PROVINCE"],
        height=600,
        mapbox_style="carto-positron",
        zoom=6)
    fig.update_geos(fitbounds="locations")
    fig.layout.coloraxis.colorbar.title = get_translation(
        fr="Nombres de cas/100K past [d-17,d-4] days",
        en="Number of cases/100K past [d-17,d-4] days")
    fig.layout.coloraxis.colorbar.titleside = "right"
    fig.layout.coloraxis.colorbar.ticks = "outside"
    fig.layout.coloraxis.colorbar.tickmode = "array"
    fig.update_traces(hovertemplate=gettext(
        gettext(
            "incidence:<b>%{customdata[0]}<br>pop:<b>%{customdata[1]}<br><b>%{customdata[2]}"
        )))
    fig.update_layout(template="plotly_white", margin=dict(l=0, r=0, t=5, b=0))
    return fig
Ejemplo n.º 22
0
def get_regional_map(df_regioni, regions_map_json, cmap, data_selected,
                     data_selected_label):
    fig = px.choropleth_mapbox(
        data_frame=df_regioni,
        geojson=regions_map_json,
        locations='codice_regione',
        featureidkey='properties.reg_istat_code_num',
        color=data_selected,
        color_continuous_scale=cmap,
        range_color=(0, math.ceil(df_regioni[data_selected].max() + 1)),
        hover_data=["increased_cases", "increased_tamponi", data_selected],
        mapbox_style="carto-positron",
        zoom=4,
        center={
            "lat": 42.00107394,
            "lon": 10.3283498
        },
        #opacity=1,
        animation_frame="giorno",
        labels={
            data_selected: data_selected_label,
            "giorno": "Giorno",
            'data': 'Data',
            "growth_rate": "Growth Rate",
            "increased_cases": "Nuovi Casi",
            "increased_tamponi": "Nuovi Tamponi Effettuati",
            "codice_regione": "Codice Regione"
        },
        height=600,
    )
    return fig
Ejemplo n.º 23
0
def map_provinces():
    fig = px.choropleth_mapbox(df_prov_tot,
                               geojson=geojson_provinces,
                               locations="PROVINCE",
                               color='CASES_PER_THOUSAND',
                               color_continuous_scale="deep",
                               range_color=(range_min, range_max),
                               featureidkey="properties.proviso",
                               center={
                                   "lat": 50.641111,
                                   "lon": 4.668889
                               },
                               height=400,
                               mapbox_style="carto-positron",
                               zoom=6,
                               labels={
                                   'CASES_PER_THOUSAND':
                                   gettext('Cases per thousand inhabitants')
                               })

    fig.update_geos(fitbounds="locations")
    fig.layout.coloraxis.colorbar.titleside = 'right'
    fig.update_traces(hovertemplate=gettext(
        "<b>%{properties.name}</b><br>%{z:.3f} cases per 1000 inhabitants"))
    fig.update_layout(template="plotly_white", margin=dict(l=0, r=0, t=0, b=0))
    return fig
Ejemplo n.º 24
0
def get_map(selected_test, selected_year, selected_mod):
    query = '''
        SELECT *
        FROM fact_estu_prgm_departamento
        WHERE prueba = '{0}'
        AND year = {1}
    '''.format(selected_test, selected_year)

    map_df = pd.read_sql_query(query, con=engine)

    fig = px.choropleth_mapbox(map_df,
                               geojson=departamentos,
                               locations='estu_prgm_departamento',
                               color=selected_mod,
                               color_continuous_scale="Viridis",
                               center={
                                   'lat': 4.3,
                                   'lon': -74.1
                               },
                               mapbox_style="carto-positron",
                               zoom=4.2,
                               labels=dict(presentation_module,
                                           **presentation_column_short_names))

    fig.update_layout(title="Colombia",
                      margin={
                          "r": 0,
                          "t": 0,
                          "l": 0,
                          "b": 0
                      },
                      paper_bgcolor="#F8F9F9",
                      plot_bgcolor="#F8F9F9")
    return fig
Ejemplo n.º 25
0
def get_map(ix = "r"):
    risk_str = ""
    if ix == "r":
        risk_str = "Risk index"
        colormap='Reds'
    elif ix == "ic":
        risk_str = "Peak ICU/ICU beds"
        colormap='Blues'
    elif ix == "mi":
        risk_str = "Fatalities/population"
        colormap='Greens'
    elif ix == "tf":
        risk_str = "Fatalities"
        colormap='Magenta'
    fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color=risk_str,
                            color_continuous_scale = colormap,
                            range_color=(df.quantile(0.05)[risk_str], df.quantile(0.95)[risk_str]),
                            mapbox_style="carto-positron",
                            zoom=3, center = {"lat": 37.0902, "lon": -95.7129},
                            opacity=0.5,
                            labels={'risk':'County risk'}
                            )
    fig.update_layout(
        margin=dict(l=0, r=0, t=0, b=0),
        plot_bgcolor='rgba(0, 0, 0, 0)',
        paper_bgcolor='rgba(0, 0, 0, 0)',)
    return fig
Ejemplo n.º 26
0
 def _make_map(self, data, geo_data):
     fig = px.choropleth_mapbox(data,
                                geojson=geo_data,
                                locations='id',
                                color='DurationOfExistenceInMonths',
                                hover_data=('DurationOfExistenceInMonths',
                                            'name'),
                                color_continuous_scale="OrRd",
                                mapbox_style="carto-positron",
                                zoom=6,
                                range_color=(0, 100),
                                center={
                                    'lat': 52.1,
                                    'lon': 19.4
                                },
                                opacity=1,
                                labels={
                                    'DurationOfExistenceInMonths':
                                    'Średni czas życia',
                                    'name': 'Nazwa'
                                },
                                height=842)
     fig.update_layout(margin={
         "r": 0,
         "t": 0,
         "l": 0,
         "b": 0
     },
                       hoverlabel=dict(bgcolor="white", font_size=16))
     return fig
Ejemplo n.º 27
0
def update_figure(candidate, metric, date):
    global dates
    date_str = dates[date]
    global preprocessed_data
    if preprocessed_data is None:
        preprocessed_data = prepare_data()
        logging.info('Data is ready')
    if candidate == candidates[-1]:
        candidate = 'ratio'
    metric = metric + '_' + candidate
    logging.info('Prepearing the figure...')
    fig = px.choropleth_mapbox(
        preprocessed_data[preprocessed_data['created_at'] == date_str],
        geojson=us_states,
        locations='state',
        color=metric,
        #color_continuous_scale="Viridis",
        #animation_frame="created_at",
        range_color=(0, preprocessed_data[metric].max()),
        mapbox_style="carto-positron",
        zoom=3,
        center={
            "lat": 37.0902,
            "lon": -95.7129
        },
        opacity=0.5,
    )
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}, )
    logging.info('Figure is ready')
    return [fig]