Python / Dash-TypeError:“ Figure”类型的对象不可JSON序列化

时间:2018-09-18 00:18:49

标签: python google-visualization jupyter-notebook data-visualization

我正在尝试构建一个简单的应用程序。目的是创建一个下拉列表并将该下拉列表用作过滤器。过滤后的数据将显示在Google地图上。这是我的代码:

不幸的是,它一直给我以下错误消息:“ TypeError:“ Figure”类型的对象不可JSON序列化”。我遵循相同的格式,使用下拉菜单过滤数据集,代码运行正常。仅在我尝试映射数据时才会出现此问题。但是对于这个学校项目,我必须在Python中使用Google Map API,这是到目前为止我唯一知道的方法。如果您可以建议如何解决该问题,将不胜感激。非常感谢

#import necessary packages
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import gmaps
import gmaps.datasets
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
gmaps.configure(api_key="") #Google Map API
df = pd.read_excel('') #read the Map file in

def create_data(choice): #this function takes in a keyword and filter the dataframe based on the keyword
    data = df[df['Primary'] == choice]
    return data

def create_map(data): #create a map with customized annotations
    info_box_template = """
        <dl>
        <dt>Community Partner: </dt><dd>{CommunityPartner}</dd>
        <dt>Address: </dt><dd>{Address}</dd>
        </dl>
        """
    dict1 = data.to_dict('records')
    partner_info = [info_box_template.format(**partner) for partner in dict1]
    marker_layer = gmaps.symbol_layer(data[['Lat', 'Longitude']], info_box_content=partner_info,
                                     fill_color='rgba(0, 255, 0, 0.0)', stroke_color='rgba(200, 0, 0, 0.4)', scale=2)

    omaha_coordinates = (41.25, -95.99)
    fig = gmaps.figure(center=omaha_coordinates, zoom_level=12) #create the foundation map focused on Omaha first
    fig.add_layer(marker_layer)
    return fig

app = dash.Dash('') #create a Dash app

available_indicators = df.Primary.unique() #create a list of unique primary areas for options in the app.layout section later

app.layout = html.Div([ #this part is the dropdown
    dcc.Dropdown(
        id='dropdown-a',
        options=[{'label': i, 'value': i} for i in available_indicators], 
    multi=False, placeholder='Filter by Primary Mission...'),
    html.Div(id='output-a')
])

@app.callback( #this callback is to create the result of the dropdown action
    dash.dependencies.Output('output-a', 'children'),
    [dash.dependencies.Input('dropdown-a', 'value')])

def update_map(dropdown_value): #update the table
    word = create_data(dropdown_value)
    fig = create_map(word)
    return fig

app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"}) #the css to make it more beautiful

if __name__ == '__main__':
    app.run_server()

0 个答案:

没有答案