lizard
lizard

Reputation: 179

Plotly Scattermapbox lines not showing but no error message

I've written the following code that maps straight lines with a start and end latitude and longitude. While the code runs without an error message, the figure generated does not show any of the lines despite showing the legend.

fig = go.Figure(
    [
        go.Scattermapbox(
            name=g[0],
            lat=np.array(g[1][["lat.start", "lat.end"]]),
            lon=np.array(g[1][["lon.start", "lon.end"]]),
            mode="lines",
        )
        for g in df.groupby("attribute")
    ]
)

I've looked through the documentation of Scattermapbox, but nothing suggests that lat and lon cannot take arrays, so I'm not sure why they are not showing up.

Upvotes: 0

Views: 890

Answers (2)

r-beginners
r-beginners

Reputation: 35115

It looks like the problem was already solved, but I created a line graph on mapbox using a data frame. The basic structure is achieved by looping through the latitude and longitude in each line of the dataframe. plotly will prepare you for the question as an example of visualization with maps.

import plotly.graph_objects as go
import pandas as pd

token = open("mapbox_api_key.txt").read()

df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
jfk = df_flight_paths[df_flight_paths['airport1'] == 'JFK']
jfk.reset_index(inplace=True)

jfk
    index   start_lat   start_lon   end_lat     end_lon     airline     airport1    airport2    cnt
0   63  40.639751   -73.778926  26.072583   -80.152750  AA  JFK     FLL     112
1   85  40.639751   -73.778926  36.080361   -115.152333     AA  JFK     LAS     112
2   92  40.639751   -73.778926  33.942536   -118.408074     AA  JFK     LAX     548
3   128     40.639751   -73.778926  41.979595   -87.904464  AA  JFK     ORD     56
4   155     40.639751   -73.778926  32.733556   -117.189657     AA  JFK     SAN     56
5   163     40.639751   -73.778926  18.439417   -66.001833  AA  JFK     SJU     168

fig = go.Figure()

for i in range(len(jfk)):
    fig.add_trace(
        go.Scattermapbox(
            mode='lines',
            lat=[jfk['start_lat'][i], jfk['end_lat'][i]],
            lon=[jfk['start_lon'][i], jfk['end_lon'][i]],
            line=dict(width=jfk['cnt'][i]/50, color='red'),
            name=jfk['airport2'][i]
        )
    )

fig.update_layout(
    title='From jfk airport to airports',
    margin ={'l':0,'t':0,'b':0,'r':0},
    mapbox = {
        'accesstoken': token,
        'center': {'lon': -90.00, 'lat': 40.639},
        'style': 'open-street-map',
        'zoom': 4})

fig.show()

enter image description here

Upvotes: 0

lizard
lizard

Reputation: 179

Instead of plotting a 2D array, a 1D array can be passed instead:

lat=np.ravel(np.array(g[1][["lat.start", "lat.end"]])),
lon=np.ravel(np.array(g[1][["lon.start", "lon.end"]])),

Upvotes: 1

Related Questions