更新菜单后不可见打印痕迹

时间:2018-07-07 21:26:22

标签: python plotly

我正在美国地图上绘制散布图(51个州的51条迹线,包括DC和4个不同年份的4条迹线)。我有2个按钮的updatemenus,它们可以在一个带有图例的散点图(51条迹线)和一个底部带有滑块的散点图(4条迹线)之间切换。我最初设置4条迹线(年)visible = False是因为我只希望最初显示51条迹线,但是当我单击按钮切换到带有滑块的散点图并设置前51条迹线visible = False和最后4条迹线时visible = [True, False, False, False]我的踪迹在地图上都不可见。

不确定为什么会这样。当我在第一次创建散点图时设置cities_year visible = True时(即它们最初可见)时,会出现迹线,但我不希望这样,因为那样我便将所有散点图绘制在每个散点图的顶部两次其他。

以下是一些用于创建数据集的代码:

data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')
data = data.iloc[:400] # Keep only first 400 samples
data.loc[:100, 'year'] = '1990'
data.loc[100:200, 'year'] = '1991'
data.loc[200:300, 'year'] = '1992'
data.loc[300:, 'year'] = '1993'

我正在使用plotly 2.7.0版和离线绘图 这是我的密谋代码:

cities = []
for state in data['name'].value_counts().index:
    data_sub = data.loc[data['name'] == state]
    city = dict(
        type = 'scattergeo',
        visible = True,
        locationmode = 'USA-states',
        lon = data_sub['lon'],
        lat = data_sub['lat'],
        mode = 'markers',
        marker = dict(
            size = 8,
            color = "rgb(255, 102, 102)",
            opacity = 0.4,
            line = dict(
                width=0.5,
                color='rgb(255, 102, 102)'
            )
        ),
        name = state
    )
    cities.append(city)

cities_year = []
for year in sorted(data.year.value_counts().index):
    data_sub = data.loc[data['year'] == year]
    city = dict(
        type = 'scattergeo',
        visible = False,
        locationmode = 'USA-states',
        lon = data_sub['lon'],
        lat = data_sub['lat'],
        mode = 'markers',
        marker = dict(
            size = 8,
            color = "rgb(255, 102, 102)",
            opacity = 0.4,
            line = dict(
                width=0.5,
                color='rgb(255, 102, 102)'
            )
        ),
        name = str(year)
    )
    cities_year.append(city)

slider = [dict(active = 0,
               pad = dict(t = 1),
               steps = [dict(args = ["visible", ([False] * len(cities)) + [True, False, False, False]], 
                             label = "1990",
                             method = "restyle"
                            ),
                        dict(args = ["visible", ([False] * len(cities)) + [False, True, False, False]],
                             label = "1991", 
                             method = "restyle"
                            ),
                        dict(args = ["visible", ([False] * len(cities)) + [False, False, True, False]],
                             label = "1992",
                             method = "restyle"
                            ),
                        dict(args = ["visible", ([False] * len(cities)) + [False, False, False, True]],
                             label = "1993",
                             method = "restyle"
                            )
                       ]
              )
         ]

updatemenus = list([
    dict(type="buttons",
         active=0,
         buttons=list([   
            dict(label = 'states',
                 method = 'update',
                 args = [dict(visible = ([True] * len(cities)) + ([False] * len(cities_year))),
                         dict(sliders = [],
                              showlegend = True)]),
            dict(label = 'years',
                 method = 'update',
                 args = [dict(visible = ([False] * len(cities)) + [True, False, False, False]),
                         dict(sliders = slider,
                              showlegend = False)])
        ]),
     )
])

layout = dict(
    title = 'myplot',
    geo = dict(
        scope='usa',
        projection=dict(type='albers usa'),
        showland=True,
        showlakes = True,
        landcolor = 'rgb(217, 217, 217)',
        subunitwidth=1,
        countrywidth=1,
        subunitcolor="rgb(255, 255, 255)",
        countrycolor="rgb(255, 255, 255)"
    ),
    updatemenus=updatemenus
)

trace_data = cities + cities_year
fig = dict(data=trace_data, layout=layout)
iplot(fig, validate=False)

1 个答案:

答案 0 :(得分:0)

问题:如果我理解正确,则运行以上code时:iplot()创建带有两个标记为“ scattergeo()”的两个buttonsstates图和'years'。在这两个按钮中,“ states”按钮处于活动状态并显示其图形(带有“红点”和legend)。 “ years”按钮对应于带有slider选项(years 19901993)的图。现在,单击此“ years”按钮时,期望在“ maps”上出现“红色点”(对于year 1990)。但是,这不会发生。

运行以上代码时的绘图 Plot when above code is run

单击“年”按钮时,没有数据点的问题图 enter image description here

尝试的解决方案:

visible的{​​{1}} True的{​​{1}} city中的dictionary设置为cities_year(在下面)时,则问题已经解决了。也就是说,运行list后,该图将显示两个按钮。现在,当'traces'codeyears时,它将在button clicked处显示带有slider的'红色点'。设置year可能很重要,因为它可能是在加载或显示1990的第一时间。 (visible=True; plot

Jupyter Notebook 5.0.0

运行Python 3.6.6之后的图: enter image description here

现在,单击“年”按钮时,图为: enter image description here

编辑-1 ---------------

cities_year = [] for year in sorted(data.year.value_counts().index): data_sub = data.loc[data['year'] == year] city = dict( type = 'scattergeo', visible = True, 仍然无法正常工作。但是找到了一种解决方法,可以仅使用code来选择slider

legends

enter image description here

编辑-2 ---------------

问题仍然没有解决,但是下面的代码可能有助于缩小发现错误的范围。在下面的year中,有两个样本数据集:(1) dict(label = 'years', method = 'restyle', args = [dict(visible = ([False] * len(cities)) + [True, True, True, True]), dict(sliders = slider, showlegend = False)]) 和(2)code。为了简单起见,每个go.Scatter()中总共只有go.Scattergeo() 5个。请注意,尽管用于生成示例数据集的rows不同,但以下代码可绘制上述两个数据集。它表明dataframe正常工作,并且code存在问题中提到的问题。

导入库

go.Scatter()

go.Scattergeo()创建数据

import datetime
from datetime import date
import pandas as pd
import numpy as np
from plotly import __version__
%matplotlib inline

import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot 
init_notebook_mode(connected=True)

init_notebook_mode(connected=True)
cf.go_offline()

import plotly.offline as pyo
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import json

go.Scatter()创建数据

# Create random numbers
x = np.random.randn(100)
y = 10 + np.random.randn(100)
z = np.linspace(-3,2,100)
df = pd.DataFrame({'x':x, 'y':y, 'z':z})
df.head(2)

# Create traces
trace1 = go.Scatter(visible = True, x=df.x, y=df.y, mode='markers', name='trace1', marker=dict(color='red'))
trace2 = go.Scatter(visible = True, x=df.x, y=df.z, mode='markers', name='trace2', marker=dict(color='black'))

trace3 = go.Scatter(visible = False, x=df.x, y=df.y*df.y, mode='markers', name='trace3', marker=dict(color='blue'))
trace4 = go.Scatter(visible = False, x=df.x, y=df.z*0.5, mode='markers', name='trace4', marker=dict(color='orange'))
trace5 = go.Scatter(visible = False, x=df.x, y=df.z*df.z, mode='markers', name='trace5', marker=dict(color='purple'))

# Create list of traces 
data = [trace1, trace2, trace3, trace4, trace5]
下面的

go.Scattergeo()是以上两个数据集的共同点

# Create dataframe for cities
df = pd.DataFrame({'name': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia'],
                  'pop': [8287238, 3826423, 2705627, 2129784, 1539313],
                  'lat': [40.730599, 34.053717, 41.875555, 29.758938, 39.952335],
                  'lon': [-73.986581, -118.242727, -87.624421, -95.367697, -75.163789],
                   'year': [1990, 1991, 1992, 1993, 1991]
                })


# Create city traces manually without for-loop
trace1 = go.Scattergeo(visible=True,name = 'trace1',locationmode = 'USA-states',
                   lon = df[df['name']=='New York']['lon'], lat = df[df['name']=='New York']['lat'], 
                   mode = 'markers',marker = dict(size=10, symbol='circle-open', color = "red")) 
trace2 = go.Scattergeo(visible=True,name = 'trace2',locationmode = 'USA-states',
                   lon = df[df['name']=='Los Angeles']['lon'], lat = df[df['name']=='Los Angeles']['lat'], 
                   mode = 'markers',marker = dict(size=10, symbol='circle-open', color = "red")) 


trace3 = go.Scattergeo(visible=False, name = 'trace3', locationmode = 'USA-states',
                   lon = df[df['year']==1990]['lon'], lat = df[df['year']==1990]['lat'],
                   mode = 'markers',marker = dict(size=20, symbol='circle-open', color = "blue")
                  ) 
trace4 = go.Scattergeo(visible=False, name = 'trace4', locationmode = 'USA-states',
                   lon = df[df['year']==1991]['lon'], lat = df[df['year']==1991]['lat'],
                   mode = 'markers',marker = dict(size=20, symbol='circle-open', color = "blue")
                  )  
trace5 = go.Scattergeo(visible=False, name = 'trace5', locationmode = 'USA-states',
                   lon = df[df['year']==1992]['lon'], lat = df[df['year']==1992]['lat'],
                   mode = 'markers',marker = dict(size=20, symbol='circle-open', color = "blue")
                  ) 

# Create list of traces
data = [trace1, trace2, trace3, trace4, trace5]

具有Code

的地块

(左:# Create slider sliders = [dict(active=-1, pad = {"t": 1}, currentvalue = {"prefix": "Plot Number: "}, execute=True, steps = [ dict(args = ["visible", [False, False, True, False, False]], label = "trace3", method = "restyle" ), dict(args = ["visible", [False, False, False,True, False]], label = "trace4", method = "restyle" ), dict(args = ["visible", [False, False, False, False, True]], label = "trace5", method = "restyle" ) ], transition = 0 ) ] # Create updatemenus updatemenus = list([ dict( buttons= list([ dict( args = [ {'visible': (True, False, False, False, False)}, {'sliders':[], 'showlegend': True, 'title': 'Plots only'} ], label = 'single_plot', method = 'update' ), dict( args = [ {'visible': (False, False, True, False, False)}, {'sliders':sliders, 'showlegend': True, 'title': 'Plots with slider'} ], label = 'multi_plots', method = 'update' ) ]), direction = 'left', pad = {'r': 10, 't': 10}, showactive = True, type = 'buttons', x = 0.1, xanchor = 'left', y = 1, yanchor = 'top' )]) # Create layout layout = go.Layout(title='Chart') #, geo=dict(scope='usa')) #<--uncomment for Scattergeo() ... optional layout['updatemenus'] = updatemenus # Plot data fig = go.Figure(data=data, layout=layout) pyo.offline.plot(fig) 'go.Scatter()'的图;右:button'single_plot'的图)

请注意,此处按“ multi_points” button后,正确显示了右侧数据点上的图。

enter image description here

具有multi_plots

的地块

(左:button'go.Scattergeo()'的图;右:button'single_plot'的图)

请注意,按“ button”按钮后,右侧图中的数据点丢失了。

enter image description here