如何仅使用单个滑块处理所有子图图形? [Python-Dash]

时间:2019-02-04 14:23:51

标签: python-3.x plotly-dash

我正在为子图使用子图结构,并且我想通过使用Slider在x轴上进行调整。我尝试同时遍历我的图表,但这不起作用。回调例程破坏了子图结构(通过plotly.tools.make_subplots创建)。

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from plotly import tools
from plotly import graph_objs as go

fig = tools.make_subplots(rows=2, shared_xaxes=True)
fig.add_scatter(x=[1,2,3], y=[2,1,2])
fig.add_scatter(x=[1,2,3], y=[5,3,3], yaxis='y2')


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[

dcc.Graph(
    id='graph1',
    figure = fig
),

dcc.Slider(
    id='temp-slider',
    min=0,
    max=10,
    step=0.2,
    value=0
)

])

@app.callback(
    Output('graph1','figure'), [Input('temp-slider','value')]
)

def update_graph(value): 
    out = dict(
        data = fig.data,
        layout = dict(
            xaxis = dict(
                range = [value,value+1]
            )
        )
    )
    return out


if __name__ == '__main__':
    app.run_server(debug=True)

我需要一个子图,通过使用相同的滑块来对两个图进行排列

1 个答案:

答案 0 :(得分:0)

由于您重新创建图形,因此子图布局丢失了,请仅更新现有range的特定figure属性。请参考下面的示例代码,让我知道这是否可以解决您的问题。

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from plotly import tools
from plotly import graph_objs as go

fig = tools.make_subplots(rows=2, shared_xaxes=True)
fig.add_scatter(x=[1,2,3], y=[2,1,2])
fig.add_scatter(x=[1,2,3], y=[5,3,3], yaxis='y2')
fig.layout.xaxis.dtick=0.5

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[

dcc.Graph(
    id='graph1',
    figure = fig
),

dcc.Slider(
    id='temp-slider',
    min=0,
    max=10,
    step=0.2,
    value=0
)

])

@app.callback(
    Output('graph1','figure'), [Input('temp-slider','value')]
)

def update_graph(value): 
    fig.layout.xaxis.range = [value,value+1]
    return fig


if __name__ == '__main__':
    app.run_server(debug=True)