Search code examples
pythongeolocationplotlylocationchoropleth

How to use choropleth map function with python plotly library to visualize by continent?


I am trying to create a choropleth map to visualize each continent's total pageviews from dataframe but plotly library function'S locationmode parameter does not have it.Is there any way to solve this problem ? When I use the 'country names' for the locationmode it does not work.

st.subheader("Continent's Total Pageviews Choropleth Map")
fig2 = go.Figure(data= go.Choropleth(
locations= df1['continent'],
z = df1['total_pageviews'].astype(float),
locationmode = 'country names',
colorscale = 'Reds',
colorbar_title = "Total Pageviews",
))
fig2.update_layout( width = 1100 , height = 500 )
st.write(fig2)

Solution

    • get GEOJSON of continents
    • build a geopandas dataframe, integrate the page views data
    • simple mapbox plot
    import requests
    import geopandas as gpd
    import numpy as np
    import plotly.express as px
    
    cont = requests.get(
        "https://gist.githubusercontent.com/hrbrmstr/91ea5cc9474286c72838/raw/59421ff9b268ff0929b051ddafafbeb94a4c1910/continents.json"
    )
    gdf = gpd.GeoDataFrame.from_features(cont.json())
    
    gdf = gdf.assign(
        total_pageviews=np.random.randint(10 ** 7, 10 ** 9, len(gdf))
    ).set_index("CONTINENT")
    
    px.choropleth_mapbox(
        gdf,
        geojson=gdf.geometry,
        locations=gdf.index,
        color="total_pageviews",
        mapbox_style="carto-positron",
        color_continuous_scale="Reds",
        opacity=0.5,
        zoom=1,
    ).update_layout(margin={"l": 0, "r": 0, "b": 0, "t": 0})