如何对比绘制两个DataFrame同一列的value_counts柱状图
解决方案
要实现两个DataFrame同一列的归一化分布对比柱状图,且每个类别下显示两个柱子(分别对应两个DF),无需合并原始DataFrame,可按以下方式操作:
步骤1:统一统计数据的类别索引
先分别获取两列的归一化统计结果,再统一索引补全缺失类别,确保所有可能的类别都被包含:
import pandas as pd import matplotlib.pyplot as plt import numpy as np # 替换为你的真实DataFrame df1 = pd.DataFrame({'A': ['X', 'Y', 'X', 'Z', 'X', 'Y']}) df2 = pd.DataFrame({'A': ['Y', 'Y', 'Z', 'Z', 'Z']}) # 获取归一化统计并按索引排序 counts_df1 = df1['A'].value_counts(normalize=True).sort_index() counts_df2 = df2['A'].value_counts(normalize=True).sort_index() # 合并所有类别,缺失类别的统计值补0 all_categories = counts_df1.index.union(counts_df2.index) counts_df1 = counts_df1.reindex(all_categories, fill_value=0) counts_df2 = counts_df2.reindex(all_categories, fill_value=0)
步骤2:用Matplotlib绘制分组柱状图
手动控制柱子位置和颜色,实现更灵活的布局:
# 设置柱子宽度与X轴位置 bar_width = 0.35 x_pos = np.arange(len(all_categories)) # 创建画布与轴对象 fig, ax = plt.subplots() # 绘制两个DataFrame的柱状图,指定颜色 df1_bars = ax.bar(x_pos - bar_width/2, counts_df1, bar_width, color='green', label='DataFrame 1') df2_bars = ax.bar(x_pos + bar_width/2, counts_df2, bar_width, color='blue', label='DataFrame 2') # 可选:给柱子添加数值标签 ax.bar_label(df1_bars, fmt='%.2f') ax.bar_label(df2_bars, fmt='%.2f') # 设置图表属性 ax.set_xlabel('类别') ax.set_ylabel('归一化占比') ax.set_title('列A的分布对比') ax.set_xticks(x_pos) ax.set_xticklabels(all_categories) ax.legend() # 调整布局避免标签截断 plt.tight_layout() plt.show()
简化方式:用Pandas直接绘制
若无需精细布局控制,可将统计结果合并为一个DataFrame,直接调用Pandas绘图方法:
# 合并统计结果为统一DataFrame combined_stats = pd.DataFrame({ 'DataFrame 1': counts_df1, 'DataFrame 2': counts_df2 }) # 绘制分组柱状图并指定颜色 combined_stats.plot(kind='bar', color=['green', 'blue'], title='列A的分布对比') plt.xlabel('类别') plt.ylabel('归一化占比') plt.legend(title='数据源') plt.tight_layout() plt.show()
两种方式都能保证X轴标签完全对应,同一类别下的两个柱子分别展示两个DataFrame的统计结果。
内容的提问来源于stack exchange,提问作者ArieAI
相关产品推荐
相关产品推荐

