如何在Plotly子图中为第二条曲线添加轴?

时间:2016-07-27 19:11:07

标签: layout plotly axes subplot multiple-axes

我有三条痕迹,其中一条在一个子图中,另外两条在另一个子图中。我希望子图中的每条迹线都有一条明显的y轴,带有2条迹线。

例如,我有

fig = plotly.tools.make_subplots(rows=2, cols=1, shared_xaxes=True)
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 1)
fig.append_trace(trace3, 2, 1)
fig['layout'].update(height=200, width=400)

产生

enter image description here

当我没有子图时,我可以使用

为第二个轨迹获得第二个轴
layout = go.Layout(
    yaxis=dict(
        title='y for trace1'
    ),
    yaxis2=dict(
        title='y for trace2',
        titlefont=dict(
            color='rgb(148, 103, 189)'
        ),
        tickfont=dict(
            color='rgb(148, 103, 189)'
        ),
        overlaying='y',
        side='right'
    )
)
fig = go.Figure(data=data, layout=layout)

产生

enter image description here

但是我无法弄清楚如何在第一个例子中看到第一个子图,看起来像第二个例子中的图:第二个跟踪的不同轴在那里。

如何在Plotly子图中为第二条迹线添加轴?

1 个答案:

答案 0 :(得分:0)

这是一种解决方法,但似乎有效:

import plotly as py
import plotly.graph_objs as go
from plotly import tools
import numpy as np

left_trace = go.Scatter(x = np.random.randn(1000), y = np.random.randn(1000), yaxis = "y1", mode = "markers")
right_traces = []
right_traces.append(go.Scatter(x = np.random.randn(1000), y = np.random.randn(1000), yaxis = "y2", mode = "markers"))
right_traces.append(go.Scatter(x = np.random.randn(1000) * 10, y = np.random.randn(1000) * 10, yaxis = "y3", mode = "markers"))

fig = tools.make_subplots(rows = 1, cols = 2)
fig.append_trace(left_trace, 1, 1)
for trace in right_traces:
  yaxis = trace["yaxis"] # Store the yaxis
  fig.append_trace(trace, 1, 2)
  fig["data"][-1].update(yaxis = yaxis) # Update the appended trace with the yaxis

fig["layout"]["yaxis1"].update(range = [0, 3], anchor = "x1", side = "left")
fig["layout"]["yaxis2"].update(range = [0, 3], anchor = "x2", side = "left")
fig["layout"]["yaxis3"].update(range = [0, 30], anchor = "x2", side = "right", overlaying = "y2")

py.offline.plot(fig)

生成此内容,其中trace0位于yaxis1上绘制的第一个子图中,trace1trace2位于第二个子图中,绘制在yaxis2上(0-3)和yaxis3(0-30)分别为: enter image description here

当跟踪附加到子图时,x轴和y轴似乎被覆盖,或者我对this discussion的理解。