Python Plotly:使用下拉菜单在Choropleth映射和散点图之间切换

时间:2018-09-27 11:19:44

标签: python plotly visualization

我不熟悉使用plotly,并且尝试使用python和plotly构建动态可视化。我希望能够使用下拉菜单在世界choropleth图和散点图之间切换。

到目前为止,通过从数据变量中删除Choropleth映射或散点图跟踪,我已经能够成功获得一个下拉菜单来显示和显示所需的标签,甚至显示单个图。问题是,无论我选择哪种菜单选项,当我尝试同时执行两个图时,在散点图的顶部绘制了Choropleth图。

输出的screenshot

我正在寻找解决方案的区域

plotly reference并仔细检查了更新菜单和布局部分。

回顾了绘图的python tutorial page for dropdowns并在我的代码中实现了部分建议,重点是更新方法。

我发现一个StackOverflow page似乎很接近我需要的答案,但还不完全一样。

最后,我还搜索了plotly community forum

代码

请注意,我在一开始就删除了一部分代码,例如导入和数据。

scatterplot = go.Scatter(

    y = df2['Renewable energy consumption (% of total final energy consumption) 2015'],
    x = df2['GDP per capita, PPP (constant 2011 international $) 2015'],
    mode='markers',
    ids=df2['Country Name'],
    showlegend = False,
      marker = dict(
          size = 8,
          color = np.random.randn(500),
        ),
      textfont = dict(
        size = 14,
        color = 'black')
)

choropleth_map = dict(
        type = 'choropleth',
        locations = df['ISO3166_alpha3'],
        z = df['renewables_mtoe'],
        text = df['Country'],
        colorscale = [[0,"rgb(106, 240, 255)"],[0.10,"rgb(106, 199, 255)"],[0.70,"rgb(50, 100, 255)"],[0.93,"rgb(0, 43, 198)"],\
          [0.99999,"rgb(0, 24, 109)"],[1,"rgb(220, 220, 220)"]],
        autocolorscale = False,
        reversescale = True,
        marker = dict(
            line = dict (
                color = 'rgb(180,180,180)',
                width = 0.5
            ) ),
        colorbar = dict(
            title = 'mtoe<br>',
            tickfont = dict(
                size = 16),
            titlefont = dict(
                size = 16)),
)

data = [choropleth_map, scatterplot]

updatemenus = list([
    dict(active=0,
         buttons=list([   
            dict(label = 'choropleth_map',
                 method = 'update',
                 args = [{'visible': [True,False]},
                         {'title': 'The Map'}]),
            dict(label = 'scatterplot',
                 method = 'update',
                 args = [{'visible': [False,True]},
                         {'title': 'Scatterplot'}]),
        ]),       
    )
])

layout = dict(title='default', showlegend=False,
                  updatemenus=updatemenus,
        geo = dict(showframe = True,
                    showcoastlines = False,
                    showland = True,
                    landcolor = '#dcdcdc',
                    projection = dict(type = 'natural earth'))
)

fig = dict( data=data, layout=layout )
plotly.offline.iplot(fig, validate=True)

在此先感谢所有可以提供帮助的人。我花了几天的时间来解决这个问题,它甚至促使我在StackOverflow上发表第一篇文章。

0 个答案:

没有答案