簡體   English   中英

Python中的Plotly動畫滑塊

[英]Plotly animated slider in Python

我試圖在Jupyter筆記本中重新創建這個例子。

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

但是收到了這個錯誤:

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']

動畫運行時沒有將滑塊dict添加到布局中,滑塊可見且可操作,但不會更改圖形。 當我移動滑塊時,它會在控制台中產生以下錯誤:

Uncaught (in promise) undefined

更新:

我檢查了你的圖表,我有時會觀察到下面的錯誤。

未定義(承諾)未定義

這個錯誤可能是由於故意錯過了一個點擊或其他事件,但這是在plotly.js文件內部,如果你去Plotly Slider動畫鏈接和slider animation部分,點擊播放並點擊滑塊,同時播放是運行我們得到這個錯誤,即使我點擊暫停我得到這個錯誤。 但是如果我再次按下游戲,動畫會繼續播放,因此沒有重大影響! 只是事件處理不當。

因此,就你所提供的圖表而言,我可以讓動畫正常工作,盡管我得到了錯誤( Uncaught (in promise) undefined )我仍然可以播放動畫!

您可以使用iplot(fig, validate=False)plot(fig)來顯示Python中帶動畫的圖形!

回答:

錯誤是因為layout對象有一個名為sliders的屬性而不是slider ,所以無論你在布局下使用slider ,請更改此,此圖也很復雜,也可能有其他錯誤,請分享代碼,進行調試。 但是現在這將是我的答案。

之前:

['layout']['slider'] 

后:

['layout']['sliders']

請替換與布局相關的所有slider屬性,這些屬性需要更改為sliders

參考文獻:

我已經處理了與此特定滑塊動畫Plot​​ly圖形相關的問題。 如果需要,請參考他們,他們可能有助於解決您的問題!

  1. Plotly動畫氣泡圖在劇情中沒有數據
  2. Plotly錯誤無效的圖或數據參數
  3. Puply在Jupyter Notebook上離線創建動畫

由於該筆記本中存在拼寫錯誤,您可能會遇到此錯誤。 它應該是sliders而不是slider ,請參閱文檔

另一個錯誤似乎也是由這個錯字造成的。 看起來這個代碼在一個事件處理程序中,只要你移動滑塊就會觸發它。

所以線下(和類似的):

figure['layout']['slider']

應更正為:

figure['layout']['sliders']

以下是該示例的代碼:

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()))

注意:奇怪但是代碼也成功執行了上面提到的拼寫錯誤!

演示輸出。

你需要plotly >= 2.0.0嘗試pip install plotly --upgrade

正如其他人所說,文檔不正確。 但是,簡單地更換所有slidersliders仍然會給出錯誤。 因此,這是一個自包含的例子。

http://nbviewer.jupyter.org/gist/empet/365cf202391bf7a58021388fadd52004

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM