首页 > 解决方案 > Plotly:ValueError:layout.slider 的“steps”属性收到的元素无效

问题描述

我用 matplotlib 做了一个简单的折线图,现在我想用 plotly 制作它,这样我就可以添加一个滑块,这样我就可以迭代几年而不是一个静态图,这将更具交互性。

到目前为止,这是我的代码。

df_summed = df_pre_2003.groupby(['year']) ['nAllNeonic'].sum().reset_index()
q=df_summed.year
r=df_summed.nAllNeonic
data = [dict(
        visible = False,
        #line=dict(color='#00CED1', width=6),
        #name = ' = '+str(step),
        x = q,
        y = r
)]
print(data)
#data[0] seems off but not getting an index out of range error so leaving for now
data[0]['visible'] = True
steps=[]
for i in range (0,11,len(q)):
    steps.append(q)   
    step=dict(
        method = 'restyle',  
        args = ['visible', [False] * len(data)],
    )
    step['args'][1][i] = True # Toggle i'th trace to "visible"
    steps.append(step)
sliders=[dict(
    active = 11,
    currentvalue = {"prefix": "Year: "},
    #pad = {"t": 50},
    steps = steps
)]
layout = dict(sliders=sliders)
fig = dict(data=data, layout=layout)
plot(fig, filename='test slider')

当我运行它时,我收到此错误:

为 layout.slider 的“步骤”属性收到无效元素

Invalid elements include: 
[0     1991
1     1992
2     1993
3     1994
4     1995
5     1996
6     1997
7     1998
8     1999
9     2000
10    2001
11    2002
Name: year, dtype: int64]

'steps' 属性是 Step 实例的元组,可以指定为: - plotly.graph_objs.layout.slider.Step 实例的列表或元组 - 字符串/值属性的列表或元组传递给 Step 构造函数 支持的 dict 属性:args、execute、label 等

我不明白为什么它告诉我,因为这正是我想用滑块走过的岁月。当我打印数据时,我得到了这个(这是正确的):

[{'visible': False, 'x': 0     1991
1     1992
2     1993
3     1994
4     1995
5     1996
6     1997
7     1998
8     1999
9     2000
10    2001
11    2002
Name: year, dtype: int64, 'y': 0          0.0
1          0.0
2          0.0
3      11207.2
4      82134.0
5     101002.5
6     185898.7
7     166324.4
8     140227.8
9     133949.2
10    143690.4
11    168746.2
Name: nAllNeonic, dtype: float64}]

当我打印步骤时给了我这个:

[0     1991
1     1992
2     1993
3     1994
4     1995
5     1996
6     1997
7     1998
8     1999
9     2000
10    2001
11    2002
Name: year, dtype: int64, {'method': 'restyle', 'args': ['visible', [True]]}]

似乎它应该可以工作,但我收到了那个错误。任何见解都会很棒。谢谢!另外,作为旁注,我正在关注这个例子。https://plot.ly/python/sliders/

标签: pythonplotly

解决方案


推荐阅读