繁体   English   中英

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

[英]Plotly traces not visible after updating menu

我正在美国地图上绘制散点图(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设置visible = True时(即,它们最初可见),但会显示轨迹,但是我不希望这样做,因为那样的话,我cities_year所有散点图cities_year绘制两次。

这是一些创建数据集的代码:

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和脱机打印这是我的plotly代码:

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)

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

运行上面的代码时绘制 运行上面的代码时绘制

单击“年”按钮时没有数据点的问题图 在此处输入图片说明

尝试的解决方案:

如果在city dictionary cities_year listtraces list的“ visible设置为“ True (下),那么该问题就解决了。 也就是说,运行code后,该图将显示两个按钮。 现在,“当yearsbuttonclicked ,它显示了“红点”为与slideryear 1990 设置visible=True可能很重要,因为它可能是在加载或显示plot时的第一个实例。 Jupyter Notebook 5.0.0 ; Python 3.6.6

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后绘制: 在此处输入图片说明

现在,单击“年”按钮时,图为: 在此处输入图片说明

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

slider仍然无法正常工作。 但是找到了一种仅使用legends选择year

    dict(label = 'years',
         method = 'restyle',
         args = [dict(visible = ([False] * len(cities)) + [True, True, True, True]),
                 dict(sliders = slider,
                      showlegend = False)])

在此处输入图片说明

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

问题仍然没有解决,但是下面的代码可以帮助缩小发现错误的范围。 在下面的code中,有两个示例数据集:(1) go.Scatter()和(2) go.Scattergeo() 为了保持简单,每个dataframe总共只有5 rows 注意,尽管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是以上两个数据集的通用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()绘制

(左: buttonsingle_plot ”的图;右: buttonmulti_plots ”的图)

注意,按“ multi_points” button后,右侧数据点上的图可以正确显示。

在此处输入图片说明

go.Scattergeo()绘制的图

(左: buttonsingle_plot ”的图;右: buttonmulti_plots ”的图)

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM