如何用Python为大规模语音数据集创建堆叠条形图
堆叠条形图问题的解决方案
问题本质
你用seaborn.barplot+dodge=False的方式是让同x轴位置的不同组件条重叠,而非堆叠。seaborn的barplot默认对每组数据计算统计量(默认均值),大样本下的置信区间渲染加上重叠效果,就出现了灰色块。要做堆叠条形图,必须先按x轴和组件分组聚合总时长,再基于聚合后的数据绘图。
解决步骤
1. 先聚合数据
原始数据有6200行,同一ps_med_frequency+component组合下存在多条hours记录,必须先求和得到每组的总时长:
# 分组求和并转宽格式,方便堆叠绘图 agg_df = meta_dataframe.groupby(['ps_med_frequency', 'component'])['hours'].sum().unstack(fill_value=0)
2. 用Pandas快速生成堆叠图
Pandas自带的plot方法支持直接生成堆叠条形图,代码简洁:
import matplotlib.pyplot as plt # 绘制堆叠图 ax = agg_df.plot(kind='bar', stacked=True, figsize=(12, 6)) # 配置轴和标题 ax.set(xlabel='ps_med_frequency', ylabel='Total Hours', title='Speech Duration by Frequency & Component') # 调整图例位置,避免遮挡 ax.legend(title='Component', bbox_to_anchor=(1.02, 1), loc='upper left') plt.tight_layout() plt.show()
3. Matplotlib手动绘制(更灵活)
如果需要自定义样式,用Matplotlib手动堆叠:
import matplotlib.pyplot as plt x_vals = agg_df.index x_pos = range(len(x_vals)) bottom = [0]*len(x_pos) # 逐个绘制每个组件的条形,堆叠在之前的条形上方 for comp in agg_df.columns: plt.bar(x_pos, agg_df[comp], bottom=bottom, label=comp) bottom = [b + val for b, val in zip(bottom, agg_df[comp])] # 配置轴和标签 plt.xlabel('ps_med_frequency') plt.ylabel('Total Hours') plt.title('Speech Duration by Frequency & Component') plt.xticks(x_pos, x_vals, rotation=45) plt.legend(title='Component', bbox_to_anchor=(1.02, 1), loc='upper left') plt.tight_layout() plt.show()
重要提示
- 聚合是关键:不先聚合的话,原始数据的重复条目会导致绘图逻辑混乱,出现异常色块。
- 交互式缩放:只要你的Matplotlib用的是交互式后端(比如TkAgg、Qt5Agg),绘图后直接用鼠标滚轮或工具栏的缩放按钮即可操作。
内容的提问来源于stack exchange,提问作者Senne Van den Broeck
相关产品推荐
相关产品推荐

