因此请考虑以下具有多个 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 轴的图,并且我希望当用户单击相应的曲线时,轴“隐藏”和“取消隐藏”。感谢您的帮助/指导。
最佳答案
- 使用此技术https://community.plotly.com/t/dash-callback-on-legend-item-clicked/36672/3
- 以下dash应用使y轴在图例点击事件中可见/不可见
- 已生成一个图形,该图形可创建与迹线一样多的 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/