繁体   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