我想设置一个按钮,在线性、对数和开方之间更改 3 个子图的 Y 轴。
来自 @vestland 对我之前问题的回答:从下拉菜单或按钮中将 sqrt 设置为 y 轴刻度-Python/Plotly https://stackoverflow.com/questions/66226542/set-sqrt-as-yaxis-scale-from-dropdown-or-button-python-plotly,我有一个可行的解决方案,为每个子图(lin、log、sqrt)绘制 3 条线,并通过按钮控制可见的线。
然而,下载的绘图的 HTML 反应性不是很好,所以我在想:
对于对数和线性使用 y.axis.type 更好,并且每个子图仅使用可见(True,False)。
这是工作示例代码,它使用控制链接的按钮创建 3 个子图
#@title EXAMPLE SQRT axis change { form-width: "20px" }
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
df = px.data.gapminder().query("year == 2002 or year == 2007 ")
#3 subplots with one legend linking all
fig = make_subplots(1, 3)
for country, grp in df.groupby (["country"]):
grp1= grp.query("year == 2002 ")
fig.add_trace(go.Scatter(x=grp1["gdpPercap"], y=grp1["lifeExp"], legendgroup=country, visible = True,mode='markers', name = country), col=1, row=1)
fig.add_trace(go.Scatter(x=grp1["gdpPercap"], y=np.sqrt(grp1["lifeExp"]), legendgroup=country, visible = False, mode='markers', name = country), col=1, row=1)
fig.add_trace(go.Scatter(x=grp1["gdpPercap"], y=np.log10(grp1["lifeExp"]), legendgroup=country, visible = False, mode='markers', name = country), col=1, row=1)
#adding a second plot that has the same labels and from legend are selected togheter.
grp2= grp.query("year == 2007 ")
fig.add_trace(go.Scatter(x=grp2["gdpPercap"], y=grp2["lifeExp"], legendgroup=country, visible = True,mode='markers',name = country, showlegend=False), col=2, row=1)
fig.add_trace(go.Scatter(x=grp2["gdpPercap"], y=np.sqrt(grp2["lifeExp"]), legendgroup=country, visible = False, mode='markers',name = country, showlegend=False), col=2, row=1)
fig.add_trace(go.Scatter(x=grp2["gdpPercap"], y=np.log10(grp2["lifeExp"]), legendgroup=country, visible = False, mode='markers',name = country,showlegend=False), col=2, row=1)
#Adding third plot
fig.add_trace(go.Scatter(x=grp2["gdpPercap"], y=grp2["pop"], legendgroup=country, visible = True,mode='markers',name = country, showlegend=False), col=3, row=1)
fig.add_trace(go.Scatter(x=grp2["gdpPercap"], y=np.sqrt(grp2["pop"]), legendgroup=country, visible = False, mode='markers',name = country, showlegend=False), col=3, row=1)
fig.add_trace(go.Scatter(x=grp2["gdpPercap"], y=np.log10(grp2["pop"]), legendgroup=country, visible = False, mode='markers',name = country,showlegend=False), col=3, row=1)
# buttons for updatemenu
buttons = [dict(method='restyle',
label='linear',
visible=True,
args=[{'label': 'linear',
'visible':[True, False, False],
}
]),
dict(method='restyle',
label='log',
visible=True,
args=[{'label': 'log',
'visible':[False, False, True],
}
]),
dict(method='update',
label='sqrt',
visible=True,
args=[{'label': 'linear',
'visible':[False, True, False],
}
])]
# specify updatemenu
um = [{'buttons':buttons,
'direction': 'down'}
]
fig.update_layout(updatemenus=um)
fig.show()