Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Plotly maps

  • Various map types and overlays are available.

  • Open Street Map is open for use without a token.

  • Overlays include scatter, lines, densities, etc.

  • Choropleths (coloured map sections) can be used as overlays or as separate plots when a GeoJSON formated dictionary of map polygons are available.

Map

  • Various maps with user defined overlays are available, e.g., scatter_map.

  • From Plotly version 5.24, Mapbox-es are deprecated, e.g., scatter_mapbox.

    • Writer has, as of 16. November 2024, not made the switch yet.

    • In most cases, switching between map and mapbox does not require other code changes.

Loading...
Loading...

A local example from Ås

Loading...
Loading...
Figure({
    'data': [{'customdata': array([['Restaurant', 59.6647728, 10.7896737],
                                   ['Restaurant', 59.6646628, 10.7887347],
                                   ['Restaurant', 59.6654962, 10.7953659],
                                   ['Restaurant', 59.6642813, 10.7922755],
                                   ['Restaurant', 59.6636019, 10.7929767],
                                   ['Kiosk', 59.6637434, 10.7932373],
                                   ['Restaurant', 59.663465, 10.7935577],
                                   ['Café', 59.6646862, 10.7908304],
                                   ['Café', 59.663324, 10.7943351]], dtype=object),
              'hovertemplate': ('<b>%{hovertext}</b><br><br>lat' ... '{customdata[0]}<extra></extra>'),
              'hovertext': array(['Sushiko Ås', "Charlie's Diner", "Jojo's Pizza", 'Desi Zaiqa',
                                  'Babylon Pizza', 'NT kiosk', 'Aas Bistro', 'Whytes Coffee',
                                  'Station kiosk Ås'], dtype=object),
              'lat': {'bdata': ('m6JtRhfVTUAUb66rE9VNQF9Ov/ou1U' ... 'XOa+zUTUAfjflvFNVNQHJTA83n1E1A'),
                      'dtype': 'f8'},
              'legendgroup': '',
              'lon': {'bdata': ('ywV4HFCUJUDUcNsI1ZMlQAy1ATM6ly' ... 'rhMU2WJUB+XeG455QlQDkhGRezliVA'),
                      'dtype': 'f8'},
              'marker': {'color': 'green'},
              'mode': 'markers',
              'name': '',
              'showlegend': False,
              'subplot': 'map',
              'type': 'scattermap'}],
    'layout': {'height': 600,
               'legend': {'tracegroupgap': 0},
               'map': {'center': {'lat': np.float64(59.66422595555556), 'lon': np.float64(10.792331888888889)},
                       'domain': {'x': [0.0, 1.0], 'y': [0.0, 1.0]},
                       'zoom': 14},
               'mapbox': {'center': {'lat': np.float64(59.66422595555556), 'lon': np.float64(10.792331888888889)},
                          'style': 'open-street-map',
                          'zoom': 14},
               'margin': {'b': 0, 'l': 0, 'r': 0, 't': 0},
               'template': '...',
               'width': 700}
})

Interacting with a Plotly map in Streamlit

Selecting points

import pandas as pd
import plotly.express as px
import streamlit as st

# Local restaurants and cafes
restaurants = pd.read_csv('../D2Dbook/data/restaurants.csv')

fig_restaurants = px.scatter_map(
    restaurants,
    lat="lat",
    lon="lon",
    hover_name="name",
    hover_data=["type","lat","lon"],
    color_discrete_sequence=["green"],
    # Size of sequence
    size=[10]*len(restaurants),
    size_max=8,
    zoom=14,
    height=600,
    width=700,
)
fig_restaurants.update_layout(mapbox_style="open-street-map")
fig_restaurants.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

# If "restaurant" is not in the session state, initialize it
st.title("Local Restaurants and Cafes")

st.plotly_chart(fig_restaurants, key = "restaurant", on_select="rerun", use_container_width=False)
st.subheader("")
st.subheader("Clicked Restaurant Info")
if st.session_state["restaurant"]:
    st.json(st.session_state["restaurant"])

Choropleths

  • A pure choropleth can be plotted using a GeoJSON file.

  • In addition a DataFrame containing the map region properties to use for colouring and hover information is needed.

Loading...

Choropleth with map

Loading...

Choropleth and pin

  • Using Folium, one can extract latitudes and longitudes from choropleth overlayed maps.

  • If the GeoJSON is large, expect some latency when clicking.

Choropleth_pin.png
Loading...
Notebook Cell