Function to make a Plotly Scattermapbox with multiple trajectories failed, Plotly, List Comprehension
I’m trying to create the data
plotly property using list understanding Scattermapbox
This is df:
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
df = pd. DataFrame(
{"BOROUGH": ['MANHATTAN','MANHATTAN','MANHATTAN','QUEENS', 'QUEENS', 'QUEENS'],
"CALL_QTY":[100, 10, 5, 15, 30, 45],
"lat":[40.75, 40.72, 40.73, 40.72, 70.71, 40.721],
"lng":[-73.99, -73.98, -70.97, -73.74, -73.73, -73.72]})
This is the tuple I’m going to iterate over :
u_sel = [list(a) for a in zip(['MANHATTAN', 'QUEENS'], # names
['blue', 'orange'], # colors
[0.6, 0.7])] # opacity
This is the function I created to understand using a list:
def scattermap_data(df, u_sel):
return([go. Scattermapbox(
lat = df.loc[df['BOROUGH']==b].lat.astype('object'),
lon = df.loc[df['BOROUGH']==b].lng.astype('object'),
mode = 'markers',
marker = dict(
size=df.loc[df['BOROUGH']==b]. CALL_QTY,
sizeref=0.9,
sizemode='area',
color=color,
opacity=opacity
)
)] for b, color, opacity in u_sel
)
Question: When I try to run the following command:
data = scattermap_data(df, u_sel)
layout = go. Layout(autosize=False,
mapbox= dict(
accesstoken=mapbox_access_token,
zoom=10,
style = 'dark',
center= dict(
lat=40.721319,
lon=-73.987130)
),
title = "O God, Why?")
fig = dict(data=data, layout=layout)
py.iplot(fig, filename='tmapbox')
ValueError:
Invalid value of type 'builtins.generator' received for the 'data' property of
Received value: <generator object scattermap_data.<locals>.<genexpr> at 0x000000000A72AF68>
My question: I have the impression that this single df will be broken down into two scattermapbox tracked elements of the element – the structure of data
, which would look like this:
data = [trace1, trace2]
(This looks similar in format to many plotly examples, where the trace list forms the fig
parameter of dict
in data
.)
If I am interested in go. Scattermapbox
does two separate traces, so this example does work, but I have several blocks that require this multi-tracking property, and I don’t want to repeat the code for each block (i.e. make 2 different trace
instances for each block). I feel like I’m close to getting it to work, but I just need a few tweaks.
Auxiliary information: Plotly v. 3.3.0, python 3.6, I’m new to list understanding and plotly, thanks a lot for any help.
EDIT: Added import
declaration to prevent hindering anyone.
edit2: Improved problem statement, title
Solution
I
figured out my question: I should use list()
instead of square brackets in the return value of the function.
def scattermap_data(df, u_sel):
return(list(go. Scattermapbox(
lat = df.loc[df['BOROUGH']==b].lat.astype('object'),
lon = df.loc[df['BOROUGH']==b].lng.astype('object'),
mode = 'markers',
marker = dict(
size=df.loc[df['BOROUGH']==b]. CALL_QTY,
sizeref=0.9,
sizemode='area',
color=color,
opacity=opacity
)
) for b, color, opacity in u_sel)
)