Black Lives Matter. Please consider donating to Black Girls Code today.

Scattermapbox with a colorbar legend

I’m plotting multi-color lines (trajectories) on a map, where color represents movement speed.
for now, my legend looks like this:
asgddg
Can I use a gradient color legend like those described here: https://plot.ly/python/colorscales/
With a trajectories on a map?

Also, since I didn’t find a way to pass an array of colors to a Line object, I’m plotting multi-colored line in a loop, where each segment is a new Scattermapbox object

Hi @eyebp,

You can’t do this directly, but you could use a hack of using the marker.colorscale of the first line trace.

import plotly.plotly as py
import plotly.graph_objs as go

# mapbox_access_token = 'MAPBOX_TOKEN'

data = [
    go.Scattermapbox(
        lat=['45.5017', '46.9027'],
        lon=['-73.5673', '-73.5673'],
        mode='lines+markers',
        marker=dict(
            size=0,
            showscale=True,
            colorscale=[[0, 'green'],
                        [1, 'red']],
            cmin=0,
            cmax=50
        ),
        line={'color': 'red'},
    ),
    go.Scattermapbox(
        lat=['45.5017', '46.9027'],
        lon=['-74.5673', '-74.5673'],
        mode='lines',
        line={'color': 'green'},
    )
]

layout = go.Layout(
    autosize=True,
    showlegend=False,
    hovermode='closest',
    mapbox=dict(
        accesstoken=mapbox_access_token,
        bearing=0,
        center=dict(
            lat=45,
            lon=-73
        ),
        pitch=0,
        zoom=5
    ),
)

fig = go.FigureWidget(data=data, layout=layout)
fig

Note that the first trace has:

  • mode set to lines+markers (markers is needed here for the color scale to be able to be turned on)
  • marker.size set to 0 so that markers don’t actually show up
  • marker.showscale set to True to turn on colorbar
  • marker.colorscale, marker.cmin, marker.cmax to configure colorscale and color range

And layout has show_legend=False to turn off the lines legend.

The caution here is that you’re totally responsible for making sure that the colorscale corresponds to your line colors.

Hope that helps get you started!
-Jon

3 Likes