Search code examples
pythonpython-3.xplotlyplotly-python

How to get a legend displayed for Plotly Scattergeo?


I hacked together this code to plot lat and lon coordinates on a map, and the code works pretty darn well, but I can't seem to get the legend displayed, so it's hard to tell what I'm actually looking at.

import pandas as pd
import pandas_bokeh
import matplotlib.pyplot as plt
import pgeocode
import geopandas as gpd
from shapely.geometry import Point
from geopandas import GeoDataFrame
pandas_bokeh.output_notebook()
import plotly.graph_objects as go

nomi = pgeocode.Nominatim('us')

df_melted['Latitude'] = (nomi.query_postal_code(df_melted['my_zip'].tolist()).latitude)
df_melted['Longitude'] = (nomi.query_postal_code(df_melted['my_zip'].tolist()).longitude)


df_melted['colors'] = df_melted['value'].groupby(df_melted['value']).transform('count')
print(df_melted.shape)
print(df_melted.head())

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd

fig = go.Figure(data=go.Scattergeo(
        lon = df_melted['Longitude'],
        lat = df_melted['Latitude'],
        text = df_melted['value'],
        marker_color = df_melted['colors']
        ))

fig.update_layout(
    autosize=False,
    width=1000,
    height=1000,
    title = 'Footprints Compared Based on Lat & Lon Coordinates)',
    geo_scope='usa',
    showlegend=True
    )

fig.update_layout(legend=dict(
    orientation="h",
    yanchor="bottom",
    y=1.02,
    xanchor="right",
    x=1
))
fig.show()

enter image description here

When I run the code, I see a nice map of the US, but there is not legend, even though I'm using this small script directly below, which came straight from the Plotly documentation.

legend=True & showlegend=True

Both gave me errors. Any idea how to get the legend to show up here?


Solution

    • have used earthquake data to be able to simulate df_melted with compatible columns
    • there really is only one missing parameter: marker_coloraxis="coloraxis"
    • also changed showlegend=False

    full working example using OP plotting code

    import pandas as pd
    import matplotlib.pyplot as plt
    import geopandas as gpd
    from shapely.geometry import Point
    from geopandas import GeoDataFrame
    import plotly.graph_objects as go
    import requests
    
    res = requests.get(
        "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojson"
    )
    
    us = (
        gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
        .loc[lambda d: d["iso_a3"].eq("USA"), "geometry"]
        .values[0]
    )
    gdf = gpd.GeoDataFrame.from_features(res.json(), crs="epsg:4386").loc[
        lambda d: d.intersects(us)
    ]
    df_melted = pd.DataFrame(
        {
            "Latitude": gdf["geometry"].y,
            "Longitude": gdf["geometry"].x,
            "colors": gdf["mag"],
            "value": gdf["place"],
        }
    )
    fig = go.Figure(
        data=go.Scattergeo(
            lon=df_melted["Longitude"],
            lat=df_melted["Latitude"],
            text=df_melted["value"],
            marker_color=df_melted["colors"],
            marker_coloraxis="coloraxis",
        )
    )
    
    fig.update_layout(
        autosize=False,
        width=400,
        height=400,
        title="Footprints Compared Based on Lat & Lon Coordinates)",
        geo_scope="usa",
        showlegend=False,
    )
    
    fig.update_layout(
        legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
    )
    fig.show()
    
    

    enter image description here