Python实现单图多柱状图:按列总和与非零值数量分组绘制
实现方案
步骤1:导入所需库
首先导入数据处理和绘图的核心库:
import pandas as pd import matplotlib.pyplot as plt
步骤2:创建目标DataFrame
按照题目给出的结构生成数据集:
df2 = pd.DataFrame({'URL': ['A','B','C','D','E','F'], 'X': [5,0,7,1,0,6], 'Y': [21,0,4,7,9,0], 'Z':[11,0,8,4,0,0]})
步骤3:计算统计指标
针对X、Y、Z三列,分别计算数值总和和非零值数量:
# 指定需要统计的列 target_cols = ['X', 'Y', 'Z'] # 计算每列的数值总和 col_sums = df2[target_cols].sum() # 计算每列的非零值数量(用ne(0)生成布尔数组,sum统计True的数量) non_zero_counts = df2[target_cols].ne(0).sum() # 将统计结果整理成结构化DataFrame stats_df = pd.DataFrame({'总和': col_sums, '非零值数量': non_zero_counts})
步骤4:绘制分组柱状图
使用matplotlib绘制分组柱状图,每个类别对应两个对比柱子:
# 设置柱子宽度 bar_width = 0.35 # 设置x轴刻度位置 x_positions = range(len(target_cols)) # 创建绘图画布 fig, ax = plt.subplots(figsize=(8, 5)) # 绘制"总和"系列柱子 bars_sum = ax.bar([pos - bar_width/2 for pos in x_positions], stats_df['总和'], width=bar_width, label='总和') # 绘制"非零值数量"系列柱子 bars_count = ax.bar([pos + bar_width/2 for pos in x_positions], stats_df['非零值数量'], width=bar_width, label='非零值数量') # 为每个柱子添加数值标签 for bar in bars_sum: height = bar.get_height() ax.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom') for bar in bars_count: height = bar.get_height() ax.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom') # 设置图表标签与标题 ax.set_xlabel('类别') ax.set_ylabel('统计值') ax.set_title('X/Y/Z列的总和与非零值数量对比') # 设置x轴刻度名称 ax.set_xticks(x_positions) ax.set_xticklabels(target_cols) # 添加图例 ax.legend() # 调整布局并显示图表 plt.tight_layout() plt.show()
效果说明
运行代码后会生成符合需求的分组柱状图:
- X轴为X、Y、Z三个类别
- 每个类别下的两个柱子分别展示该列的数值总和与非零值数量
- 柱子上方标注具体数值,直观呈现统计结果
内容的提问来源于stack exchange,提问作者ZA09
相关产品推荐
相关产品推荐

