Seaborn 的countplot 可以进行计数并自动创建适当的图例。不幸的是,这要么将条形彼此相邻(默认dodge=True),要么将它们从y=0(dodge=False)开始彼此重叠。一个想法是遍历生成的条形图并通过更改它们的 y 位置来堆叠它们。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
data = [['fruit', 'apple'],
['fruit', 'apple'],
['meat', 'ham'],
['fruit', 'banana'],
['meat', 'pork'],
['vegetable', 'lettuce']]
df = pd.DataFrame(data, columns=['General', 'Specific'])
# df_grp = df.groupby(['General', 'Specific']).agg(len).reset_index().rename(columns={0:'Count'})
ax = sns.countplot(data=df, x='General', hue='Specific', dodge=False)
bottoms = {}
for container in ax.containers:
for bar in container:
h = bar.get_height()
if not np.isnan(h) and h > 0:
x = bar.get_x()
w = bar.get_width()
if x in bottoms:
bar.set_y(bottoms[x])
bottoms[x] += h
else:
bottoms[x] = h
ax.text(x + w / 2, bottoms[x] - h / 2, f'{h:.0f}', ha='center', va='center')
ax.relim()
ax.autoscale() # recalculates the ylims due to the changed bars
ax.yaxis.major.locator.set_params(integer=True)
plt.tight_layout()
plt.show()