如何在Plotly动画滑块变更时打印当前年份(附可运行代码)
捕获Plotly动画滑块的当前选中年份
要实现捕获滑块当前年份(无论动画播放还是手动拖动),需要使用Plotly的FigureWidget创建可交互图表,通过绑定事件监听帧的变化来获取当前年份,以下是修改后的完整可运行代码:
import plotly.graph_objects as go import pandas as pd url = "https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv" dataset = pd.read_csv(url) years = ["1952", "1962", "1967", "1972", "1977", "1982", "1987", "1992", "1997", "2002", "2007"] # 生成大洲列表 continents = list(dataset["continent"].unique()) # 构建图表字典 fig_dict = { "data": [], "layout": {}, "frames": [] } # 填充布局信息 fig_dict["layout"]["xaxis"] = {"range": [30, 85], "title": "预期寿命"} fig_dict["layout"]["yaxis"] = {"title": "人均GDP", "type": "log"} fig_dict["layout"]["hovermode"] = "closest" fig_dict["layout"]["updatemenus"] = [ { "buttons": [ { "args": [None, {"frame": {"duration": 500, "redraw": False}, "fromcurrent": True, "transition": {"duration": 300, "easing": "quadratic-in-out"}}], "label": "播放", "method": "animate" }, { "args": [[None], {"frame": {"duration": 0, "redraw": False}, "mode": "immediate", "transition": {"duration": 0}}], "label": "暂停", "method": "animate" } ], "direction": "left", "pad": {"r": 10, "t": 87}, "showactive": False, "type": "buttons", "x": 0.1, "xanchor": "right", "y": 0, "yanchor": "top" } ] sliders_dict = { "active": 0, "yanchor": "top", "xanchor": "left", "currentvalue": { "font": {"size": 20}, "prefix": "年份:", "visible": True, "xanchor": "right" }, "transition": {"duration": 300, "easing": "cubic-in-out"}, "pad": {"b": 10, "t": 50}, "len": 0.9, "x": 0.1, "y": 0, "steps": [] } # 初始化数据(1952年) year = 1952 for continent in continents: dataset_by_year = dataset[dataset["year"] == year] dataset_by_year_and_cont = dataset_by_year[dataset_by_year["continent"] == continent] data_dict = { "x": list(dataset_by_year_and_cont["lifeExp"]), "y": list(dataset_by_year_and_cont["gdpPercap"]), "mode": "markers", "text": list(dataset_by_year_and_cont["country"]), "marker": { "sizemode": "area", "sizeref": 200000, "size": list(dataset_by_year_and_cont["pop"]) }, "name": continent } fig_dict["data"].append(data_dict) # 生成各年份帧数据 for year in years: frame = {"data": [], "name": str(year)} for continent in continents: dataset_by_year = dataset[dataset["year"] == int(year)] dataset_by_year_and_cont = dataset_by_year[dataset_by_year["continent"] == continent] data_dict = { "x": list(dataset_by_year_and_cont["lifeExp"]), "y": list(dataset_by_year_and_cont["gdpPercap"]), "mode": "markers", "text": list(dataset_by_year_and_cont["country"]), "marker": { "sizemode": "area", "sizeref": 200000, "size": list(dataset_by_year_and_cont["pop"]) }, "name": continent } frame["data"].append(data_dict) fig_dict["frames"].append(frame) slider_step = {"args": [ [year], {"frame": {"duration": 300, "redraw": False}, "mode": "immediate", "transition": {"duration": 300}} ], "label": year, "method": "animate"} sliders_dict["steps"].append(slider_step) fig_dict["layout"]["sliders"] = [sliders_dict] # 使用FigureWidget替代普通Figure,实现交互监听 fig = go.FigureWidget(fig_dict) # 定义帧变化回调函数,捕获当前年份 def on_frame_change(trace, frame, state): current_year = frame.name print(f"当前选中年份: {current_year}") # 后续可在此处添加基于年份生成关联图表的逻辑 # 绑定帧变化事件 fig.on_frame_change(on_frame_change) # 显示图表 fig.show()
关键修改说明
- 替换
go.Figure为go.FigureWidget:普通Figure是静态展示组件,无法监听交互事件,FigureWidget支持实时交互与事件绑定。 - 绑定
on_frame_change事件:该事件会在动画播放切换帧或手动拖动滑块切换年份时触发,通过frame.name直接获取当前选中的年份。 - 后续扩展:在回调函数中,可直接使用
current_year数据调用其他绘图逻辑,生成关联图表。
内容的提问来源于stack exchange,提问作者letdatado
相关产品推荐
相关产品推荐

