计算受访者补液案例数的出现占比并绘制柱状图
调查数据:补液决策统计与可视化
数据说明
现有一份调查数据,共包含6个场景(case),每行对应一位完成全部6个问题的受访者。字段值定义:
1.0:受访者会给予补液0.0:受访者不会给予补液
原始数据示例:
case_1 case_2 case_3 case_4 case_5 case_6 0 0.0 0.0 0.0 0.0 0.0 1.0 1 1.0 1.0 1.0 0.0 0.0 1.0 2 1.0 1.0 0.0 1.0 1.0 1.0 3 0.0 0.0 1.0 0.0 1.0 1.0 4 0.0 0.0 1.0 1.0 1.0 0.0 ... ... ... ... ... ... ... 517 1.0 1.0 0.0 1.0 0.0 1.0 518 0.0 0.0 1.0 1.0 1.0 1.0 519 1.0 1.0 1.0 0.0 1.0 1.0 520 1.0 0.0 0.0 0.0 1.0 0.0 521 0.0 1.0 0.0 1.0 1.0 1.0
需求
生成柱状图,展示不同补液次数(从未补液、仅1次补液、2次补液……至6次全部补液)的受访者占比。
实现方案(Python)
使用pandas处理数据,matplotlib绘制柱状图:
import pandas as pd import matplotlib.pyplot as plt # 加载数据(如果是本地文件,替换为pd.read_csv('你的数据文件路径.csv')) # df = pd.read_csv('survey_data.csv') # 计算每位受访者的补液次数 df['fluid_times'] = df.sum(axis=1) # 统计各次数的受访者数量,并计算占比(保留两位小数) counts = df['fluid_times'].value_counts().sort_index() percentages = (counts / counts.sum() * 100).round(2) # 绘制柱状图 plt.figure(figsize=(10,6)) bars = plt.bar(percentages.index.astype(str), percentages.values) # 给每个柱状条添加数值标签 for bar in bars: height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2., height, f'{height}%', ha='center', va='bottom') # 配置图表样式 plt.title('不同补液次数的受访者占比', fontsize=14) plt.xlabel('补液次数', fontsize=12) plt.ylabel('受访者占比(%)', fontsize=12) plt.xticks(rotation=0) plt.grid(axis='y', linestyle='--', alpha=0.7) plt.show()
代码说明
- 计算补液次数:对每行数据求和,得到每位受访者的补液总次数;
- 统计占比:按补液次数分组统计人数,再除以总人数得到对应占比;
- 可视化优化:添加数值标签让占比更直观,配置网格和标题提升图表可读性。
内容的提问来源于stack exchange,提问作者hulio_entredas
相关产品推荐
相关产品推荐

