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

使用Plotly/Seaborn实现按month、event_name分组的多重直方图绘制

双维度分组多重直方图实现方案

首先导入依赖并构造示例DataFrame:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px

# 构造示例数据
data_example = {'event_name': ['verification_1', 'verification_2', 'verification_1', 'verification_2','verification_3'],'working_time_in_hours': [10,300,50,100,50],'month':['April','April','May','May','May']}
df = pd.DataFrame(data_example)

Seaborn 实现(静态图)

提供两种常用布局,按需选择:

  • 分面布局:每个月份对应独立子图,子图内区分不同事件的工时分布
sns.set_theme(style="whitegrid")
# 按月份分面,hue参数区分事件类型,multiple="dodge"设置柱子并排展示
g = sns.FacetGrid(df, col="month", height=4, aspect=1)
g.map_dataframe(sns.histplot, x="working_time_in_hours", hue="event_name", multiple="dodge", binwidth=20)
g.add_legend()
g.set_axis_labels("工时(小时)", "计数")
plt.show()
  • 单图布局:所有维度在同一画布展示,适合快速对比
plt.figure(figsize=(8, 4))
# 若需展示每月各事件的总工时,可将x改为month,添加weights参数绑定工时字段
sns.histplot(data=df, x="month", weights="working_time_in_hours", hue="event_name", multiple="dodge", shrink=0.8)
plt.ylabel("总工时(小时)")
plt.show()

参数调整说明:将multiple="dodge"改为multiple="stack"可实现堆叠直方图效果

Plotly 实现(交互图)

生成的图表支持悬停查看数值、放大缩小、筛选指定类别等操作:

  • 分面交互直方图
fig = px.histogram(
    df, 
    x="working_time_in_hours", 
    color="event_name", 
    facet_col="month", 
    barmode="group", 
    nbins=10, 
    labels={"working_time_in_hours":"工时(小时)"}
)
fig.show()
  • 单图分组交互直方图
fig = px.histogram(
    df, 
    x="month", 
    y="working_time_in_hours", 
    color="event_name", 
    barmode="group", 
    labels={"working_time_in_hours":"总工时(小时)"}
)
fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:36:02