我正在尝试创建一个滑块,该滑块使用Python 3和Plotly控制两条轨迹。我正在使用Spyder,尽管我也尝试过为Jupyter修改相同的代码,但未成功。
这是代码示例:
import numpy as np
#import pandas as pd
#import matplotlib.pyplot as plt
import plotly as py
import plotly.graph_objs as go
#import ipywidgets as widgets
py.offline.init_notebook_mode(connected=True)
'''
Plot traces
'''
trace1 = [dict(
type = 'scatter',
visible = False,
name='Demand',
x = np.arange(0,365,1),
y = np.sin(step*np.arange(0,365,1))) for step in range(0,365,1)]
trace2 = [dict(
type = 'scatter',
visible = False,
name='Demand',
x = np.arange(0,365,1),
y = np.sin(step*np.arange(0,365,1)) + 5) for step in range(0,365,1)]
#data = trace2
data = [list(a) for a in zip(trace1, trace2)]
steps = []
for i in range(len(data)):
step = dict(
method = 'restyle',
args = ['visible', [False] * len(data)],
label = ""
)
step['args'][1][i] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(
active = 10,#What's happening here?
currentvalue = {"prefix": "Day: "}, #????
#pad = {"t": 50},
steps = steps
)]
#Add styling
layout = go.Layout(sliders=sliders,
title='Sample slider plot',
xaxis=dict(
title=‘Test’,
titlefont=dict(
family='Courier New, monospace',
size=18,
color='#7f7f7f'
)
),
yaxis=dict(
title=‘Unit’,
titlefont=dict(
family='Courier New, monospace',
size=18,
color='#7f7f7f'
)
)
)
fig = go.Figure(data=data, layout=layout)
py.offline.plot(fig, filename='Test3')
如果我分别绘制任何一条迹线,即
data = trace1
有效。但是,一旦我合并了trace1和trace2,即
data = [list(a) for a in zip(trace1, trace2)]
我收到以下错误:
The 'data' property is a tuple of trace instances
that may be specified as:
- A list or tuple of trace instances
(e.g. [Scatter(...), Bar(...)])
- A list or tuple of dicts of string/value properties where:
- The 'type' property specifies the trace type
One of: ['area', 'bar', 'barpolar', 'box',
'candlestick', 'carpet', 'choropleth', 'cone',
'contour', 'contourcarpet', 'heatmap',
'heatmapgl', 'histogram', 'histogram2d',
'histogram2dcontour', 'mesh3d', 'ohlc',
'parcats', 'parcoords', 'pie', 'pointcloud',
'sankey', 'scatter', 'scatter3d',
'scattercarpet', 'scattergeo', 'scattergl',
'scattermapbox', 'scatterpolar',
'scatterpolargl', 'scatterternary', 'splom',
'streamtube', 'surface', 'table', 'violin']
- All remaining properties are passed to the constructor of
the specified trace type
(e.g. [{'type': 'scatter', ...}, {'type': 'bar, ...}])
检查类型(trace1)显示每个跟踪是365个dict对象的列表,这些对象可以进行处理。但是,如上所述,一旦将迹线合并到“数据”对象中,就会得到列表列表,而列表列表是不可以的。
所以我的问题是:如何将trace1和trace2组合成一个对象,该对象的长度适合滑块的步长(即365),并且可以处理-诸如字典或跟踪实例列表,而不是列表列表?
我看过plotly - multiple traces using a shared slider variable和Plot.ly. Using slider control with multiple plots。不幸的是没有成功。如果跟踪对象是字典,则第一个链接有效,但是如果必须将其括在方括号中以列出“ for”循环,则该链接无效。第二个链接仅添加trace1 + trace2来创建索引长度为730的对象-也就是说,它连续地将两条迹线连接在一起,而不是将它们一起显示。
非常感谢您的帮助!