首页 > 解决方案 > python - 如何在python的Plotly图表中获取滑块的位置?

问题描述

我正在使用 plotly 库在 python 中制作图表。该图表有一个滑块,我想检索滑块的位置,以便使用它来显示其他内容(不能在绘图中完成)。有没有办法巧妙地返回滑块的位置?

在此先感谢您的帮助!

标签: pythonpython-3.xplotsliderplotly

解决方案


import plotly.express as px
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])

fig["layout"].pop("updatemenus") # optional, drop animation buttons

# Build App
app = JupyterDash(__name__)
app.layout = html.Div(
    [dcc.Graph(id="graph", figure=fig), 
     dcc.Interval(id="sliderInterval", interval=400, n_intervals=0),
     html.Div(id="whichframe", children=[]),
    ],
)

# core update of figure on change of dash slider    
@app.callback(
    Output("whichframe", "children"),
    Input("sliderInterval", "n_intervals"),
    State("graph", "figure")
)
def setFrame(n_intervals, fig):
    slider = fig['layout']['sliders'][0]
    return f"active:{slider['active']} value:{slider['steps'][slider['active']]['args'][0][0]}"

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



推荐阅读