如何在Seaborn中创建一个堆积条形图(分步骤进行)

3,073 阅读2分钟

叠加条形图是一种图表类型,它使用分为若干子条的条形图来同时显示多个变量的值。

本教程提供了一个循序渐进的例子,说明如何使用Seaborn数据可视化包在Python中创建以下的叠加条形图。

stacked bar chart in seaborn

第一步:创建数据

首先,让我们创建以下pandas数据框架,它显示了一家餐馆从周一到周五早晚接待的顾客总数。

import pandas as pd

#create DataFrame
df = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thur', 'Fri'],
                   'Morning': [44, 46, 49, 59, 54],
                   'Evening': [33, 46, 50, 49, 60]})

#view DataFrame
df

	Day	Morning	Evening
0	Mon	44	33
1	Tue	46	46
2	Wed	49	50
3	Thur	59	49
4	Fri	54	60

第2步:创建叠加条形图

我们可以使用下面的代码来创建一个堆积条形图,以直观地显示每一天的顾客总数。

import matplotlib.pyplot as plt
import seaborn as sns

#set seaborn plotting aesthetics
sns.set(style='white')

#create stacked bar chart
df.set_index('Day').plot(kind='bar', stacked=True, color=['steelblue', 'red'])

X轴显示的是一周中的哪一天,条形图显示的是每天早上和晚上有多少顾客光临餐厅。

第3步:自定义堆叠条形图

下面的代码显示了如何添加轴的标题,添加一个整体的标题,以及旋转X轴的标签以使其更容易阅读。

import matplotlib.pyplot as plt
import seaborn as sns

#set seaborn plotting aesthetics
sns.set(style='white')

#create stacked bar chart
df.set_index('Day').plot(kind='bar', stacked=True, color=['steelblue', 'red'])

#add overall title
plt.title('Customers by Time & Day of Week', fontsize=16)

#add axis titles
plt.xlabel('Day of Week')
plt.ylabel('Number of Customers')

#rotate x-axis labels
plt.xticks(rotation=45)

stacked bar chart in seaborn

注意:我们为这个图设置了seaborn风格为'白色',但是你可以在这个页面上找到seaborn绘图美学的完整列表。

其他资源

下面的教程解释了如何在Seaborn中创建其他常见的可视化图表。

如何在Seaborn中创建饼图
如何在Seaborn中创建时间序列图
如何在Seaborn中创建面积图

The postHow to Create a Stacked Bar Plot in Seaborn (Step-by-Step) appeared first onStatology.