堆叠条形图(Stacked Bar Chart)是一种用于展示多个类别数据之间关系的图表类型。在堆叠条形图中,每个条形被分为多个部分,每个部分代表一个子类别的数据。堆叠条形图可以直观地展示数据的总和以及各个子类别的分布情况。
堆叠条形图主要有两种类型:
堆叠条形图常用于以下场景:
import seaborn as sns
import matplotlib.pyplot as plt
# 示例数据
data = {
'Category': ['A', 'B', 'C'],
'Subcategory1': [10, 15, 7],
'Subcategory2': [15, 8, 12],
'Subcategory3': [7, 12, 10]
}
df = pd.DataFrame(data)
# 绘制堆叠条形图
plt.figure(figsize=(10, 6))
sns.barplot(data=df, x='Category', y='Subcategory1', color='red')
sns.barplot(data=df, x='Category', y='Subcategory2', color='green')
sns.barplot(data=df, x='Category', y='Subcategory3', color='blue')
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Stacked Bar Chart')
plt.legend(['Subcategory1', 'Subcategory2', 'Subcategory3'])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# 示例数据
categories = ['A', 'B', 'C']
subcategory1 = [10, 15, 7]
subcategory2 = [15, 8, 12]
subcategory3 = [7, 12, 10]
# 绘制堆叠条形图
fig, ax = plt.subplots(figsize=(10, 6))
bar_width = 0.35
index = np.arange(len(categories))
bar1 = ax.bar(index, subcategory1, bar_width, label='Subcategory1')
bar2 = ax.bar(index, subcategory2, bar_width, bottom=subcategory1, label='Subcategory2')
bar3 = ax.bar(index, subcategory3, bar_width, bottom=[i+j for i,j in zip(subcategory1, subcategory2)], label='Subcategory3')
ax.set_xlabel('Category')
ax.set_ylabel('Value')
ax.set_title('Stacked Bar Chart')
ax.set_xticks(index)
ax.set_xticklabels(categories)
ax.legend()
plt.show()
通过以上方法,你可以创建一个清晰且易于理解的堆叠条形图。
领取专属 10元无门槛券
手把手带您无忧上云