首页 > 解决方案 > 共享子图的所有 x 轴(行和列)

问题描述

我尝试与多个列共享子图结构的所有 x 轴,但我无法获得解决方案。使用“share_xaxes=True”,只有同一行的 x 轴被链接,我无法从子图中的数字中更改“xaxis”参数。任何的想法?

标签: pythonpython-3.xplotly-dash

解决方案


在 Plotly 文档中,您可以看到轴有一个名为scaleanchor的属性(请参阅https://plot.ly/python/reference/#layout-xaxis-scaleanchor)。您可以使用它来连接任意数量的轴。我在一个简单的子图上对其进行了测试,其中所有 x 轴都连接了 2 行和 2 列:

import plotly.plotly as py
import plotly.graph_objs as go

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

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

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


def create_figure():
    trace1 = go.Scatter(
        x=[1, 2, 3],
        y=[2, 3, 4]
    )
    trace2 = go.Scatter(
        x=[1, 2, 3],
        y=[5, 5, 5],
        xaxis='x2',
        yaxis='y2'
    )
    trace3 = go.Scatter(
        x=[1, 2, 3],
        y=[600, 700, 800],
        xaxis='x3',
        yaxis='y3'
    )
    trace4 = go.Scatter(
        x=[1, 2, 3],
        y=[7000, 8000, 9000],
        xaxis='x4',
        yaxis='y4'
    )
    data = [trace1, trace2, trace3, trace4]
    layout = go.Layout(
        xaxis=dict(
            domain=[0, 0.45],
            anchor='y'
        ),
        xaxis2=dict(
            domain=[0.55, 1],
            anchor='y2',
            scaleanchor='x'
        ),
        xaxis3=dict(
            domain=[0, 0.45],
            anchor='y3',
            scaleanchor='x'
        ),
        xaxis4=dict(
            domain=[0.55, 1],
            anchor='y4',
            scaleanchor='x'
        ),
        yaxis=dict(
            domain=[0, 0.45],
            anchor='x'
        ),
        yaxis2=dict(
            domain=[0, 0.45],
            anchor='x2'
        ),
        yaxis3=dict(
            domain=[0.55, 1],
            anchor='x3'
        ),
        yaxis4=dict(
            domain=[0.55, 1],
            anchor='x4'
        )
    )
    fig = go.Figure(data=data, layout=layout)
    return fig


app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=create_figure()
    )
])


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

推荐阅读