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

如何基于Pandas与Plotly为柱状图添加月份筛选下拉菜单

实现带月份下拉筛选的交互式Plotly柱状图

当然没问题!用Plotly搭配Dash框架就能轻松实现这个需求,下面是完整的实现步骤和代码示例,你可以根据自己的DataFrame结构调整细节:

1. 先做好依赖安装和数据预处理

首先确保你已经安装了必要的库,然后对现有DataFrame做简单处理,提取月份信息:

import dash
from dash import dcc, html, Input, Output, callback
import plotly.express as px
import pandas as pd

# 假设你的Current_Graph包含日期列(比如命名为'date'),先转换为日期格式并提取月份名称
Current_Graph['date'] = pd.to_datetime(Current_Graph['date'])  # 确保日期列是标准格式
Current_Graph['month'] = Current_Graph['date'].dt.month_name()  # 提取月份名称(如"January")

# 生成12个月份的下拉选项,按自然顺序排列
month_options = [
    {'label': 'January', 'value': 'January'},
    {'label': 'February', 'value': 'February'},
    {'label': 'March', 'value': 'March'},
    {'label': 'April', 'value': 'April'},
    {'label': 'May', 'value': 'May'},
    {'label': 'June', 'value': 'June'},
    {'label': 'July', 'value': 'July'},
    {'label': 'August', 'value': 'August'},
    {'label': 'September', 'value': 'September'},
    {'label': 'October', 'value': 'October'},
    {'label': 'November', 'value': 'November'},
    {'label': 'December', 'value': 'December'}
]

2. 构建Dash应用的交互布局

接下来创建包含下拉菜单和图表的页面布局:

app = dash.Dash(__name__)

app.layout = html.Div([
    html.H3("按月份筛选数据"),
    # 月份下拉菜单
    dcc.Dropdown(
        id='month-selector',
        options=month_options,
        value='January',  # 默认选中一月
        clearable=False,  # 禁止清空选项,保证图表始终有数据展示
        style={'width': '50%'}  # 可以自定义下拉框宽度
    ),
    # 用于展示柱状图的组件
    dcc.Graph(id='monthly-bar-chart', style={'margin-top': '20px'})
])

3. 编写回调函数实现实时更新

最后添加回调逻辑,监听下拉菜单的选择变化,自动筛选数据并更新图表:

@callback(
    Output('monthly-bar-chart', 'figure'),
    Input('month-selector', 'value')
)
def update_bar_chart(selected_month):
    # 根据选中的月份筛选数据
    filtered_data = Current_Graph[Current_Graph['month'] == selected_month]
    
    # 生成柱状图,这里的x、y列请替换成你DataFrame中实际的分类列和数值列
    # 比如你要展示不同区域的销售额,x就是'区域',y就是'销售额'
    fig = px.bar(
        filtered_data,
        x='category_column',  # 替换成你的分类列名
        y='value_column',     # 替换成你的数值列名
        title=f'{selected_month} 数据统计',
        color='category_column',  # 可选:给不同分类柱子加颜色区分
        barmode='group'           # 可选:分组柱状图样式
    )
    
    # 给图表加个平滑过渡动画,提升交互体验
    fig.update_layout(transition_duration=300)
    return fig

# 启动应用
if __name__ == '__main__':
    app.run_server(debug=True)

一些需要注意的细节:

  • 如果你的日期列不是标准格式,一定要先用pd.to_datetime()转换,否则无法正确提取月份。
  • 代码中的category_column和value_column必须替换成你Current_Graph中实际的列名,比如你要展示各产品的月度销量,x就是产品名称,y就是销量。
  • 如果你更习惯用数字月份(1-12),只需要把dt.month_name()改成dt.month,然后把下拉选项的label和value改成对应的数字即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:23:15