隐藏绘图折线图上的一条线

7 python pandas plotly

假设我有线 A、B、C、D 和 E。我希望线 A、B 和 C 出现在折线图上。我希望用户可以选择添加行 D 和 E,但默认情况下应隐藏 D 和 E。

关于如何执行此操作有什么建议吗?

例如,默认情况下我将如何隐藏澳大利亚。

import plotly.express as px

df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp", color='country')
fig.show()
Run Code Online (Sandbox Code Playgroud)

rpa*_*nai 17

您需要在每个轨迹中使用参数visible设置legendonly

import plotly.express as px
countries_to_hide = ["Australia"]
df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp", color='country')

fig.for_each_trace(lambda trace: trace.update(visible="legendonly") 
                   if trace.name in countries_to_hide else ())
fig.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述