2017-07-23 16 views
19

Próbowałem odtworzyć ten przykład w notatniku Jupyter.Plotly animowany suwak w Pythonie

https://plot.ly/python/gapminder-example/

ale otrzymuję ten błąd:

PlotlyDictKeyError: 'slider' is not allowed in 'layout' 

Path To Error: ['layout']['slider'] 

Valid attributes for 'layout' at path ['layout'] under parents ['figure']: 

    ['angularaxis', 'annotations', 'autosize', 'bargap', 'bargroupgap', 
    'barmode', 'barnorm', 'boxgap', 'boxgroupgap', 'boxmode', 'calendar', 
    'direction', 'dragmode', 'font', 'geo', 'height', 'hiddenlabels', 
    'hiddenlabelssrc', 'hidesources', 'hoverlabel', 'hovermode', 'images', 
    'legend', 'mapbox', 'margin', 'orientation', 'paper_bgcolor', 
    'plot_bgcolor', 'radialaxis', 'scene', 'separators', 'shapes', 
    'showlegend', 'sliders', 'smith', 'ternary', 'title', 'titlefont', 
    'updatemenus', 'width', 'xaxis', 'yaxis'] 

Run `<layout-object>.help('attribute')` on any of the above. 
'<layout-object>' is the object at ['layout'] 

Animacja działa bez DICT suwak dodany do układu, a suwak jest widoczna i sprawna, ale nie zmienia się wykres. Kiedy przesuń suwak produkuje następujący błąd w konsoli:

Uncaught (in promise) undefined 
+0

Która linia oznaczała błąd? –

+1

, gdy próbuję utworzyć figurę za pomocą metody go.Figure() lub gdy próbuję wykreślić postać json zbudowaną bez funkcji go.Figure(), gdy uruchomię plik offline.ilpot (

) –

Odpowiedz

7

Aktualizacja:

Sprawdziłem wykres masz, ja obserwując czasami błąd poniżej.

Uncaught (in promise) undefined

Ten błąd może przez powodu plotly brakuje kliknięcie lub inne zdarzenie, ale to jest wewnętrznie w pliku plotly.js, jeśli pójdziesz do Plotly Slider animation link i do sekcji slider animation, kliknij przycisk Play i kliknij na chwilę suwakiem gra jest uruchomiona otrzymujemy ten błąd, nawet gdy klikam na pauzie otrzymuję ten błąd. Ale animacja wciąż się odtwarza, jeśli ponownie naciskam grę, więc nie ma to większego wpływu! Po prostu zdarzenie nie jest obsługiwane prawidłowo.

Tak jak w przypadku dostarczonego wykresu, mogę sprawić, że animacja będzie działała poprawnie, mimo że dostaję błąd (Uncaught (in promise) undefined) Nadal mogę odtwarzać animację!

Możesz użyć albo iplot(fig, validate=False) lub plot(fig), aby pokazać wykresy w Pythonie z animacją!

Odpowiedź:

Błąd jest, ponieważ obiekt layout ma właściwość o nazwie sliders nie slider, więc wszędzie tam, gdzie używasz slider pod układ, należy zmienić, również ta działka jest bardzo skomplikowane i mogą mieć inne również błędy, proszę udostępnić kod, do debugowania. Ale na razie to będzie moja odpowiedź.

Przed:

['layout']['slider'] 

Po:

['layout']['sliders'] 

Proszę wymienić wszystkie slider właściwości, które są związane z układu, to trzeba zmienić na sliders.

Referencje:

mam obchodzić kwestie związane z tym szczególnym suwaka animowanego Plotly wykresie. Jeśli zajdzie taka potrzeba, skontaktuj się z nimi, aby pomóc w rozwiązaniu problemu!

  1. Plotly Animated Bubble Chart No Data in the Plot
  2. Plotly Error Invalid Figure or Data Argument
  3. Plotly Icreate Animations Offline on Jupyter Notebook
+1

Część 'ctrl + f' jest niepotrzebna i prawdopodobnie również niepoprawna. – 0xc0de

+0

Co zrobić, jeśli OP korzysta z notebooka w terminalu, a nie coś w, np. przeglądarka? – 0xc0de

+0

@ 0xc0de ok ma to –

1

Trzeba plotly >= 2.0.0 spróbować pip install plotly --upgrade

+0

To nie jest to. Mam wersję 2.0.15 i mam ten sam problem. – user14492

5

Prawdopodobnie uderzenie ten błąd z powodu literówki w tym zeszycie. Powinien być sliders zamiast slider, patrz docs.

Inny błąd również wydaje się być spowodowany przez tę literówkę. Wygląda na to, że ten kod znajduje się w procedurze obsługi zdarzeń, która uruchamia się za każdym razem, gdy przesuniesz suwak.

Więc poniżej linii (i podobnych nich):

figure['layout']['slider'] 

należy skorygować do:

figure['layout']['sliders'] 

Oto kod dla tego przykładu:

import plotly.plotly as py 
import plotly.graph_objs as go 
from plotly.grid_objs import Grid, Column 
from plotly.tools import FigureFactory as FF 

import pandas as pd 
import time 

url = 'https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv' 
dataset = pd.read_csv(url) 

table = FF.create_table(dataset.head(10)) 
py.iplot(table, filename='animations-gapminder-data-preview') 


years_from_col = set(dataset['year']) 
years_ints = sorted(list(years_from_col)) 
years = [str(year) for year in years_ints] 
years.remove('1957') 

# make list of continents 
continents = [] 
for continent in dataset['continent']: 
    if continent not in continents: 
     continents.append(continent) 

columns = [] 
# make grid 
for year in years: 
    for continent in continents: 
     dataset_by_year = dataset[dataset['year'] == int(year)] 
     dataset_by_year_and_cont = dataset_by_year[dataset_by_year['continent'] == continent] 
     for col_name in dataset_by_year_and_cont: 
      # each column name is unique 
      column_name = '{year}_{continent}_{header}_gapminder_grid'.format(
       year=year, continent=continent, header=col_name 
      ) 
      a_column = Column(list(dataset_by_year_and_cont[col_name]), column_name) 
      columns.append(a_column) 

# upload grid 
grid = Grid(columns) 
url = py.grid_ops.upload(grid, 'gapminder_grid'+str(time.time()), auto_open=False) 

figure = { 
    'data': [], 
    'layout': {}, 
    'frames': [], 
    'config': {'scrollzoom': True} 
} 

# fill in most of layout 
figure['layout']['xaxis'] = {'range': [30, 85], 'title': 'Life Expectancy', 'gridcolor': '#FFFFFF'} 
figure['layout']['yaxis'] = {'title': 'GDP per Capita', 'type': 'log', 'gridcolor': '#FFFFFF'} 
figure['layout']['hovermode'] = 'closest' 
figure['layout']['plot_bgcolor'] = 'rgb(223, 232, 243)' 

figure['layout']['sliders'] = { 
    'args': [ 
     'slider.value', { 
      'duration': 400, 
      'ease': 'cubic-in-out' 
     } 
    ], 
    'initialValue': '1952', 
    'plotlycommand': 'animate', 
    'values': years, 
    'visible': True 
} 

figure['layout']['updatemenus'] = [ 
    { 
     'buttons': [ 
      { 
       'args': [None, {'frame': {'duration': 500, 'redraw': False}, 
         'fromcurrent': True, 'transition': {'duration': 300, 'easing': 'quadratic-in-out'}}], 
       'label': 'Play', 
       'method': 'animate' 
      }, 
      { 
       'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate', 
       'transition': {'duration': 0}}], 
       'label': 'Pause', 
       'method': 'animate' 
      } 
     ], 
     'direction': 'left', 
     'pad': {'r': 10, 't': 87}, 
     'showactive': False, 
     'type': 'buttons', 
     'x': 0.1, 
     'xanchor': 'right', 
     'y': 0, 
     'yanchor': 'top' 
    } 
] 


sliders_dict = { 
    'active': 0, 
    'yanchor': 'top', 
    'xanchor': 'left', 
    'currentvalue': { 
     'font': {'size': 20}, 
     'prefix': 'Year:', 
     'visible': True, 
     'xanchor': 'right' 
    }, 
    'transition': {'duration': 300, 'easing': 'cubic-in-out'}, 
    'pad': {'b': 10, 't': 50}, 
    'len': 0.9, 
    'x': 0.1, 
    'y': 0, 
    'steps': [] 
} 

custom_colors = { 
    'Asia': 'rgb(171, 99, 250)', 
    'Europe': 'rgb(230, 99, 250)', 
    'Africa': 'rgb(99, 110, 250)', 
    'Americas': 'rgb(25, 211, 243)', 
    #'Oceania': 'rgb(9, 255, 255)' 
    'Oceania': 'rgb(50, 170, 255)' 
} 

col_name_template = '{year}_{continent}_{header}_gapminder_grid' 
year = 1952 
for continent in continents: 
    data_dict = { 
     'xsrc': grid.get_column_reference(col_name_template.format(
      year=year, continent=continent, header='lifeExp' 
     )), 
     'ysrc': grid.get_column_reference(col_name_template.format(
      year=year, continent=continent, header='gdpPercap' 
     )), 
     'mode': 'markers', 
     'textsrc': grid.get_column_reference(col_name_template.format(
      year=year, continent=continent, header='country' 
     )), 
     'marker': { 
      'sizemode': 'area', 
      'sizeref': 200000, 
      'sizesrc': grid.get_column_reference(col_name_template.format(
       year=year, continent=continent, header='pop' 
      )), 
      'color': custom_colors[continent] 
     }, 
     'name': continent 
    } 
    figure['data'].append(data_dict) 


for year in years: 
    frame = {'data': [], 'name': str(year)} 
    for continent in continents: 
     data_dict = { 
      'xsrc': grid.get_column_reference(col_name_template.format(
       year=year, continent=continent, header='lifeExp' 
      )), 
      'ysrc': grid.get_column_reference(col_name_template.format(
       year=year, continent=continent, header='gdpPercap' 
      )), 
      'mode': 'markers', 
      'textsrc': grid.get_column_reference(col_name_template.format(
       year=year, continent=continent, header='country' 
       )), 
      'marker': { 
       'sizemode': 'area', 
       'sizeref': 200000, 
       'sizesrc': grid.get_column_reference(col_name_template.format(
        year=year, continent=continent, header='pop' 
       )), 
       'color': custom_colors[continent] 
      }, 
      'name': continent 
     } 
     frame['data'].append(data_dict) 

    figure['frames'].append(frame) 
    slider_step = {'args': [ 
     [year], 
     {'frame': {'duration': 300, 'redraw': False}, 
     'mode': 'immediate', 
     'transition': {'duration': 300}} 
    ], 
    'label': year, 
    'method': 'animate'} 
    sliders_dict['steps'].append(slider_step) 

figure['layout']['sliders'] = [sliders_dict] 

py.icreate_animations(figure, 'gapminder_example'+str(time.time())) 

Uwaga: Strange ale kod wykonał dla mnie z powodzeniem także powyższą literówkę!

Demo wyjście.