在 plotly 中更新特定的子图轴

update specific subplot axes in plotly

设置:

代码 1

import numpy as np
from plotly.subplots import make_subplots
from math import exp

fig = make_subplots(2, 1)

x = np.linspace(0, 10, 1000)
y = np.array(list(map(lambda x: 1 / (1 + exp(-0.1 * x + 5)), x)))
fig.add_trace(
    go.Scatter(
        x=x,
        y=y,
        name=f'\N{Greek Small Letter Sigma}(x)',
        showlegend=True
    ),
    row=1,
    col=1
)

x = np.where(np.random.randint(0, 2, 100)==1)[0]
fig.add_trace(
    go.Scatter(
        x=x,
        y=np.zeros_like(x),
        name=f'Plot 2',
        mode='markers', 
        marker=dict(
                symbol='circle-open',
                color='green',
                size=5
            ),
        showlegend=True
    ),
    row=2,
    col=1
)
fig.show()

我试过的

我尝试在每次添加跟踪后使用 fig.update_xaxes(),但它弄乱了绘图并且没有产生所需的输出,如 Code 2.

所示

代码 2:

import numpy as np
from plotly.subplots import make_subplots
from math import exp

fig = make_subplots(2, 1)

x = np.linspace(0, 10, 1000)
y = np.array(list(map(lambda x: 1 / (1 + exp(-0.1 * x + 5)), x)))
fig.add_trace(
    go.Scatter(
        x=x,
        y=y,
        name=f'\N{Greek Small Letter Sigma}(x)',
        showlegend=True
    ),
    row=1,
    col=1
)
fig.update_xaxes(title_text='x')
x = np.where(np.random.randint(0, 2, 100)==1)[0]
fig.add_trace(
    go.Scatter(
        x=x,
        y=np.zeros_like(x),
        name=f'Plot 2',
        mode='markers', 
        marker=dict(
                symbol='circle-open',
                color='green',
                size=5
            ),
        showlegend=True
    ),
    row=2,
    col=1
)
fig.update_xaxes(title_text='active users')
fig.show()

这导致(注意 active users 打印在顶部):

我的问题:

  1. 如何将顶部绘图 x 轴的标签 xactive users 标签分配给底部绘图的 x 轴?
  2. 一般来说——如何访问单个子图的属性?

的帮助下,我能够通过在位置 row=1col=1 和 [=14] 上引用 xaxis 来解决问题=] 用于 row=2col=1 位置上的绘图。完整的解决方案在 Code 1.

代码 1:

import numpy as np
from plotly.subplots import make_subplots
from math import exp

fig = make_subplots(2, 1)

x = np.linspace(0, 10, 1000)
y = np.array(list(map(lambda x: 1 / (1 + exp(-0.1 * x + 5)), x)))
fig.add_trace(
    go.Scatter(
        x=x,
        y=y,
        name=f'\N{Greek Small Letter Sigma}(x)',
        showlegend=True
    ),
    row=1,
    col=1
)
fig['layout']['xaxis'].update(title_text='x')

x = np.where(np.random.randint(0, 2, 100)==1)[0]
fig.add_trace(
    go.Scatter(
        x=x,
        y=np.zeros_like(x),
        name=f'Plot 2',
        mode='markers', 
        marker=dict(
                symbol='circle-open',
                color='green',
                size=5
            ),
        showlegend=True
    ),
    row=2,
    col=1
)
fig['layout']['xaxis2'].update(title_text='active users')

fig.show()

干杯。