制作具有多条迹线的Plotly Scattermapbox的功能失败,Plotly,列表理解

时间:2019-01-07 21:30:11

标签: python list-comprehension plotly

我正在尝试使用列表推导来创建Plotly data的{​​{1}}属性。

这是df:

Scattermapbox

这是我要遍历的元组:

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]})

这是我创建的使用列表推导的函数:

u_sel = [list(a) for a in zip(['MANHATTAN', 'QUEENS'], # names
                              ['blue', 'orange'],      # colors
                              [0.6, 0.7])]             # opacity

问题:当我尝试运行以下命令时:

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
    )

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')

我的问题:我的印象是,单个df将分解为scattermapbox跟踪元素的两个实例-ValueError: Invalid value of type 'builtins.generator' received for the 'data' property of Received value: <generator object scattermap_data.<locals>.<genexpr> at 0x000000000A72AF68>的结构,上面类似于:

data

(这在格式上看起来与许多绘图示例类似,在这些示例中,轨迹列表构成了data = [trace1, trace2] data的{​​{1}}参数。

如果我对dict进行了两条独立的跟踪,则此示例可以工作,但是我有多个需要该多重跟踪属性的图,并且我不想为每个图重复代码(即,使两个不同的{每个情节都有{1}}个实例。我觉得我已经很接近让它起作用了,但是我只需要进行一些调整。

辅助信息:Plotly v.3.0.3,python 3.6,我是新列出列出理解和plotly的人,任何帮助将不胜感激。

edit:添加fig语句以防万一。 edit2:改进的问题陈述,标题

1 个答案:

答案 0 :(得分:1)

我发现了我的问题:在返回函数时,我应该使用list()而不是方括号。

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)
)