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

如何基于Year列过滤Plotly直方图(常规Plotly,非Dash)

实现Plotly直方图的年份动态过滤(无需Dash)

常规Plotly没有直接支持非x/y轴字段过滤的内置控件,但可以通过两种方式实现基于Year列的实时过滤:


方案1:添加下拉菜单(选择特定年份/全部年份)

通过控制图表痕迹的可见性,实现点击下拉选项切换显示不同年份的数据。适合纯HTML静态输出场景,导出后仍可交互。

代码实现

import plotly.express as px
import pandas as pd

# 构造你的数据集
df = pd.DataFrame([
    {"Procedure": "Colectomy", "Country": "China", "Year": 2019},
    {"Procedure": "Colectomy", "Country": "India", "Year": 2020},
    {"Procedure": "Appendectomy", "Country": "China", "Year": 2020},
    {"Procedure": "Appendectomy", "Country": "USA", "Year": 2010}
])

# 初始绘制包含所有数据的直方图
fig = px.histogram(df, x='Procedure', color='Country', title='手术频次统计')

# 为每个痕迹标记对应的年份
for trace in fig.data:
    # 提取当前痕迹对应的年份(基于Country和Procedure匹配)
    trace_year = df[(df['Country'] == trace.name) & (df['Procedure'] == trace.x[0])]['Year'].iloc[0]
    trace.customdata = [[trace_year]] * len(trace.x)

# 生成下拉菜单按钮
years = sorted(df['Year'].unique())
buttons = [
    # 显示全部年份的按钮
    {
        'label': 'All Years',
        'method': 'restyle',
        'args': [{'visible': [True] * len(fig.data)}]
    }
]

# 逐个添加单一年份的按钮
for year in years:
    # 确定哪些痕迹属于当前年份
    visible = [trace.customdata[0][0] == year for trace in fig.data]
    buttons.append({
        'label': str(year),
        'method': 'restyle',
        'args': [{'visible': visible}]
    })

# 将下拉菜单添加到图表布局
fig.update_layout(
    updatemenus=[{
        'buttons': buttons,
        'direction': 'down',
        'showactive': True,
        'x': 0.1,
        'xanchor': 'left',
        'y': 1.15,
        'yanchor': 'top'
    }]
)

fig.show()

方案2:添加年份范围滑块(查看某年份及以后的数据)

借助ipywidgets的交互功能,在Jupyter环境中实时过滤数据并重新绘制直方图,体验更流畅。

代码实现

import plotly.express as px
import pandas as pd
from ipywidgets import interact

# 构造数据集
df = pd.DataFrame([
    {"Procedure": "Colectomy", "Country": "China", "Year": 2019},
    {"Procedure": "Colectomy", "Country": "India", "Year": 2020},
    {"Procedure": "Appendectomy", "Country": "China", "Year": 2020},
    {"Procedure": "Appendectomy", "Country": "USA", "Year": 2010}
])

# 定义直方图更新函数
def update_histogram(min_year):
    # 过滤年份≥min_year的数据
    filtered_df = df[df['Year'] >= min_year]
    # 重新绘制直方图
    fig = px.histogram(filtered_df, x='Procedure', color='Country', 
                       title=f'手术频次统计(年份≥{min_year})')
    fig.show()

# 创建滑块交互控件
interact(update_histogram, min_year=(df['Year'].min(), df['Year'].max(), 1))

核心逻辑说明

  • 方案1通过restyle方法修改痕迹的visible属性,无需重新生成图表,适合静态HTML导出
  • 方案2通过interact绑定滑块与数据过滤函数,每次滑块变动时重新生成图表,适合Jupyter交互式分析场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:15:35