You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用Plotly动画实现柱状图切换?

在Plotly中实现点击按钮切换柱状图的动画效果

要实现点击按钮切换不同模型的柱状图(带平滑过渡动画),你需要在同一个图表实例中通过按钮触发数据更新,而不是创建两个独立的图表。核心是利用Plotly的updatemenus配置项添加交互按钮,配合过渡动画实现流畅切换。

完整实现代码

import plotly.express as px

# 定义两个模型的数据
model_data = {
    "Model 1": [0.4, 0.8],
    "Model 2": [0.6, 0.2]
}
x_labels = ["Test set 1", "Test set 2"]

# 创建初始图表(默认显示Model 1的数据)
fig = px.bar(x=x_labels, y=model_data["Model 1"], width=500)
fig.update_layout(
    xaxis_title="",
    yaxis_title="Accuracy",
    yaxis_range=[0, 1],
    # 添加切换按钮
    updatemenus=[
        dict(
            type="buttons",
            direction="right",
            x=0.7,
            y=1.2,
            buttons=[
                # 切换到Model 1的按钮
                dict(
                    label="Model 1",
                    method="restyle",
                    args=[
                        {"y": [model_data["Model 1"]]},
                        {"transition": {"duration": 500}}  # 过渡动画时长(毫秒)
                    ]
                ),
                # 切换到Model 2的按钮
                dict(
                    label="Model 2",
                    method="restyle",
                    args=[
                        {"y": [model_data["Model 2"]]},
                        {"transition": {"duration": 500}}
                    ]
                )
            ]
        )
    ]
)

fig.show()

关键说明

  • 数据整合:把两个模型的y轴数据放到字典里,方便按钮调用
  • 按钮配置:通过updatemenus添加按钮组,method="restyle"用于修改图表数据;args里指定要更新的y值,同时设置transition参数实现平滑动画
  • 动画控制:duration参数控制切换动画的快慢,数值越小切换越快,越大越平缓

点击按钮后,柱状图会带着平滑的过渡动画切换到对应模型的准确率数据,和你想要的效果一致。

内容的提问来源于stack exchange,提问作者Markus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 14:52:18