St.plotly_chart(fig) does not show px.scatter_map()

Hi everyone, I’m trying to plot a real time map of DC Metro’s Orange, Silver and Blue Line
My map code is made using plotly and I used px.scatter_map() to initialise the map, and go.Scattermap() to add traces.

However, st.plotly_chart() just displays a blank graph instead of displaying the map.
Using fig.show() displays the map correctly.

Thanks in advance!

Locally-run app
Streamlit version: 1.39.0
Python version: 3.11.1

Here’s the code snippet:

def initialize_map(line):

  stations = line.stations
  fig = px.scatter_map(stations, lat = stations.stop_lat, lon=stations.stop_lon)

  # Set layout for Mapbox
  fig.update_layout(
      autosize=True,
      hovermode='closest',
      map=dict(
          bearing=0,
          center=dict(
              lat=38.92,
              lon=-77.07
          ),
          pitch=0,
          zoom=10,
          style='light'
      ),
      showlegend=False,
      margin={"r":0,"t":0,"l":0,"b":0}  # Remove default margins
  )
  st.plotly_chart(fig)
  return fig

def plot(line, direction):
  fig = initialize_map(line)

  def plot_stations(line, direction):
      fig.add_trace(go.Scattermap(
          lat=line.stations.stop_lat,
          lon=line.stations.stop_lon,
          mode='markers+text+lines',
          marker=go.scattermap.Marker(size=9, color=line.name.lower()),  # Specify a color explicitly
          text=line.stations.station_name,
          textfont=dict(size=8, color="black", family="Open Sans Bold")
      ))

      if direction:
          cur = line.stations.iloc[0]
          fig.add_trace(go.Scattermap(
              lat=[cur.stop_lat],
              lon=[cur.stop_lon],
              mode='markers+text',
              text="Destination: ",
              textfont=dict(size=11, color="black", family="Open Sans Bold"),
              marker=dict(size=20, symbol= "circle-stroked", color="red")
          ))
      else:
          cur = line.stations.iloc[-1]
          fig.add_trace(go.Scattermap(
              lat=[cur.stop_lat],
              lon=[cur.stop_lon],
              mode='markers+text',
              text="Destination",
              textfont=dict(size=11, color="black", family="Open Sans Bold"),
              marker=dict(size=20, symbol= "circle-stroked", color="red")
          ))


  def plot_trains(line, direction):
      trains = line.trains
      trains = trains[trains["vehicle.trip.directionId"]==direction]
      stopped_trains = trains[trains["vehicle.currentStatus"]=="STOPPED_AT"]
      trains = trains[trains["vehicle.currentStatus"]!="STOPPED_AT"]

      #For stopped trains
      fig.add_trace(go.Scattermap(
              lat=stopped_trains["vehicle.position.latitude"],
              lon=stopped_trains["vehicle.position.longitude"],
              mode='markers',
              text=stopped_trains["vehicle.currentStatus"]+" "+stopped_trains["station_name"],
              marker=dict(size= 16, symbol= "rail-metro")
          ))
      
      #For trains in transit
      lat = trains["vehicle.position.latitude"]
      lon = trains["vehicle.position.longitude"]
      if direction:
          fig.add_trace(go.Scattermap(
              lat=lat,
              lon=lon,
              mode='markers',
              text=trains["vehicle.currentStatus"]+" "+trains["next_station_name_1"],
              marker=dict(size= 16, symbol= "rail-metro")
          ))
      else:
          fig.add_trace(go.Scattermap(
              lat=lat,
              lon=lon,
              mode='markers',
              text=trains["vehicle.currentStatus"]+" "+trains["next_station_name_0"],
              hoverinfo=['skip'],
              marker=dict(size= 16, symbol= "rail-metro")
          ))

  plot_stations(line, direction)
  plot_trains(line, direction)
  st.plotly_chart(fig)


linechoice = st.selectbox("Select metro line", ("Orange [Vienna Fairfax-GMU to New Carrolton]", "Silver [Ashburn to Largo]", "Blue [Franconia-Springfield to Largo]"), index=0)

if 'line' not in st.session_state:
    st.session_state.line = orangeline

if linechoice == "Orange [Vienna Fairfax-GMU to New Carrolton]":
    st.session_state.line = orangeline
elif linechoice == "Silver [Ashburn to Largo]":
    st.session_state.line = silverline
else:
    st.session_state.line = blueline

if 'direction' not in st.session_state:
    st.session_state.direction = 1

if st.button("Switch Direction"):
    st.session_state.direction = 1 if st.session_state.direction == 0 else 0


plot(st.session_state.line, st.session_state.direction)

st.write(orangeline.stations)

if st.button("Refresh Data"):
    feed_rt, predictions = get()
    st.success("Data refreshed successfully!")
1 Like

Is there any update on the issue? I am also facing the same issue.

Hi Rama,

Apparently px.scattermap only works locally and not when deployed.

The deployed version works with px.scattermapbox for which you need a free mapbox token that you can get from the mapbox website.

@Abhay5 , I am using local streamlit app only. It does not show the scatter_map. Do I need to get free mapbox token?

What is orangeline?

I just tried one of Plotly’s examples for scatter_map and it displays correctly both locally and when deployed on Community Cloud. If you’re having trouble with this map type, can you confirm if this simple example works?

# requirements.txt

plotly
import streamlit as st
import plotly.express as px
df = px.data.carshare()
fig = px.scatter_map(df, lat="centroid_lat", lon="centroid_lon",     color="peak_hour", size="car_hours",
                  color_continuous_scale=px.colors.cyclical.IceFire, size_max=15, zoom=10)
st.write(fig)
st.plotly_chart(fig, key="2")

(I just used two different commands to render it and they both work for me. The key is just there to avoid a “duplicate” error.)

Also make sure Streamlit and plotly are both upgraded to their latest versions. I had to upgrade my instance of plotly. :slight_smile: