import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
以下数据如果有需要的同学可关注公众号HsuHeinrich,回复【数据可视化】自动获取~
# 导入数据
df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/email_campaign_funnel.csv")
df.head()
# 布局
fig, ax = plt.subplots(figsize=(4, 8))
# 分组变量
group_col = 'Gender'
# 按阶段排序
order_of_bars = df.Stage.unique()[::-1]
# 为分组别量每个类别分配颜色
colors = [plt.cm.Spectral(i / float(len(df[group_col].unique()) - 1)) for i in range(len(df[group_col].unique()))]
# 遍历为每组每个阶段绘制一个条形图
for color, group in zip(colors, df[group_col].unique()):
# sns绘制条形图
sns.barplot(x='Users',
y='Stage',
data=df.loc[df[group_col] == group, :], # 筛选数据
order=order_of_bars,
color=color,
label=group,
ax=ax, # 指定轴
)
# 自定义轴
ax.set_xlabel("Users")
ax.set_ylabel("Stage of Purchase")
ax.set_title("Population Pyramid of the Marketing Funnel", fontsize=22)
# 图例
ax.legend()
plt.show()
参考:Population pyramid of a marketing funnel[1]
共勉~
[1]
Population pyramid of a marketing funnel: https://python-graph-gallery.com/web-population-pyramid/