簡體   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