python - 绘制随绘图动态变化的多个轴

标签 python plotly

因此请考虑以下具有多个 y 轴的图(取自此处 link )

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])

# Add traces
fig.add_trace(
    go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
    secondary_y=False,
)

fig.add_trace(
    go.Scatter(x=[2, 3, 4], y=[4, 5, 6], name="yaxis2 data"),
    secondary_y=True,
)

# Add figure title
fig.update_layout(
    title_text="Double Y Axis Example"
)

# Set x-axis title
fig.update_xaxes(title_text="xaxis title")

# Set y-axes titles
fig.update_yaxes(title_text="<b>primary</b> yaxis title", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> yaxis title", secondary_y=True)

fig.show()

当我们单击和取消单击“yaxis data”和“yaxis2 data”时,是否有办法使轴“隐藏”和“取消隐藏”?我需要构建一个具有超过 2 个 y 轴的图,并且我希望当用户单击相应的曲线时,轴“隐藏”和“取消隐藏”。感谢您的帮助/指导。

最佳答案

import dash
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np

# build a figure with defined number of traces, each trace using it's own yaxis
TRACES = 9
fig = go.Figure(
    [
        go.Scatter(
            x=np.linspace(0, 10, 10),
            y=np.random.uniform(1 * 10 ** y, 5 * 10 ** y, 10),
            name=str(y),
            yaxis=f"y{'' if y==0 else y+1}",
        )
        for y in range(TRACES)
    ]
).update_layout(
    {
        f"yaxis{'' if ax==0 else ax+1}": {
            "position": 1 - (ax / 20),
            "overlaying":None if ax==0 else "y",
        }
        for ax in range(TRACES)
    }
)
# some space for all the y-axes
fig = fig.update_layout(xaxis={"domain": [0, 0.4]})

# Build App
app = JupyterDash(__name__)
app.layout = dash.html.Div(
    [
        dash.dcc.Graph(id="fig", figure=fig),
    ],
)

@app.callback(
    Output("fig", "figure"), Input("fig", "restyleData"), State("fig", "figure")
)
def graphClick(clickData, fig):
    if not clickData:
        raise dash.exceptions.PreventUpdate
    yax = {
        f"yaxis{'' if tn==0 else tn+1}": {
            "visible": clickData[0]["visible"][i] != "legendonly"
        }
        for i, tn in enumerate(clickData[1])
    }
    return go.Figure(fig).update_layout(**yax)


# Run app and display result inline in the notebook
app.run_server(mode="inline")

关于python - 绘制随绘图动态变化的多个轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69748973/

相关文章:

python - django-debug-toolbar-line-profiler 只显示单行输出,没有内容

python - 在 python 中识别 windows/linux GUI 中的文本以进行自动化测试

r - 水平列出图例项并在图下方居中

python - 保存 Tensorflow 模型仅用于预测的最有效的空间/内存方法?

python - Torque PBS - 运行多个串行 Python 进程

Python pandas 自动对列进行排序

python - 输入变量值后使用 Dash(来自 Plotly)在仪表板上输出值

r - 如何链接图例和颜色选择的 plotly 轨迹?

javascript - 如何在plotly.js 的堆积面积图中显示值和名称?

python - 破折号中的图形布局