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

如何在同一柱状图中绘制两个DataFrame的value_counts结果

解决方法:对齐分类后绘制并列柱状图

你的问题核心是两个DataFrame的分类(x轴标签)未对齐,直接绘图会导致x轴按各自行索引排列,无法对应相同的Category。以下是两种可行的解决方式:

方法1:Matplotlib手动控制柱子位置

先统计两个DataFrame中每个Category的目标统计值(比如你提到的计数),将结果按Category对齐后,手动设置柱子的位置实现并列效果:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# 模拟你的数据
df1 = pd.DataFrame({
    'Category': ['Big', 'Big', 'Big', 'Normal'],
    'Value': [10, 20, 15, 5]
})
df2 = pd.DataFrame({
    'Category': ['Big', 'Normal', 'Normal'],
    'Value': [12, 8, 6]
})

# 按Category统计计数(根据你的需求,也可以换成sum/mean等)
df1_stats = df1['Category'].value_counts().sort_index()
df2_stats = df2['Category'].value_counts().sort_index()

# 合并统计结果,补全缺失的Category(用0填充)
combined_stats = pd.DataFrame({
    'df1': df1_stats,
    'df2': df2_stats
}).fillna(0)

# 设置柱子宽度与x轴位置
width = 0.35
x = np.arange(len(combined_stats.index))

# 绘制柱状图
fig, ax = plt.subplots()
bar1 = ax.bar(x - width/2, combined_stats['df1'], width, label='df1')
bar2 = ax.bar(x + width/2, combined_stats['df2'], width, label='df2')

# 配置x轴与图例
ax.set_xticks(x)
ax.set_xticklabels(combined_stats.index)
ax.legend()

# 添加柱子顶部的数值标签
def add_labels(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate(f'{int(height)}',
                    xy=(rect.get_x() + rect.get_width()/2, height),
                    xytext=(0, 3),
                    textcoords='offset points',
                    ha='center', va='bottom')

add_labels(bar1)
add_labels(bar2)

plt.tight_layout()
plt.show()

方法2:用Seaborn快速实现

将两个DataFrame合并并添加来源标识,利用Seaborn的分类绘图功能自动处理并列:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 模拟数据
df1 = pd.DataFrame({
    'Category': ['Big', 'Big', 'Big', 'Normal'],
    'Value': [10, 20, 15, 5]
})
df2 = pd.DataFrame({
    'Category': ['Big', 'Normal', 'Normal'],
    'Value': [12, 8, 6]
})

# 合并数据集并标记来源
df1['Source'] = 'df1'
df2['Source'] = 'df2'
combined_df = pd.concat([df1, df2])

# 绘制并列计数柱状图(若需统计Value的总和/均值,可改用barplot并设置estimator参数)
sns.catplot(x='Category', hue='Source', kind='count', data=combined_df)
plt.show()

问题原因说明

直接调用df.plot(kind='bar', stacked=False)时,两个DataFrame的行索引是独立的,Matplotlib会按各自的行号分配x轴位置,导致相同Category的柱子无法对齐。必须先将两个数据集的分类体系统一,确保每个Category在两个数据集中都有对应的统计值,再进行绘图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:50:18