python - No whitespace between Seaborn barplot bars
问题描述
I created a Seaborn barplot using the code below (it comes from https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
I would like all the bars to stack up without whitespace, but have been unable to do so. If I add width it complains about multiple values for width in barh. This is probably as seaborn has its own algo to determine the width. Is there anyway around it?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Read data
df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/email_campaign_funnel.csv")
# Draw Plot
plt.figure(figsize=(13, 10), dpi=80)
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 c, group in zip(colors, df[group_col].unique()):
sns.barplot(x='Users', y='Stage', data=df.loc[df[group_col]==group, :],
order=order_of_bars, color=c, label=group)
# Decorations
plt.xlabel("$Users$")
plt.ylabel("Stage of Purchase")
plt.yticks(fontsize=12)
plt.title("Population Pyramid of the Marketing Funnel", fontsize=22)
plt.legend()
plt.show()
解决方案
无论如何都不是 matplotlib 专家,所以可能有更好的方法来做到这一点。也许您可以执行以下操作,类似于此答案中的方法:
# Draw Plot
fig, ax = plt.subplots(figsize=(13, 10), dpi=80)
...
for c, group in zip(colors, df[group_col].unique()):
sns.barplot(x='Users', y='Stage', data=df.loc[df[group_col]==group, :],
order=order_of_bars, color=c, label=group, ax=ax)
# Adjust height
for patch in ax.patches:
current_height = patch.get_height()
patch.set_height(1)
patch.set_y(patch.get_y() + current_height - 1)
推荐阅读
- python - 使用 Scrapy 的 Python 网络爬虫无法填写表单
- amazon-web-services - AWS cloudfront 在 Google Chrome 中提供过时的内容?
- excel - VBA 代码没有像以前那样快速运行(这段代码从来没有花时间运行,但现在我不知道发生了什么)
- sql - 关于在 Access VBA 中使用 SQL 的 For Loop 问题
- angular - Angular - 如何从资产目录下载示例模板文件
- c# - 如何使用 c# 程序编写/控制 Xbox One 控制器
- docker - Kafka、Docker-Compose、Bootstrap 代理断开连接
- google-colaboratory - 为什么 Google Colab Pro 说我有太多的会话,而我目前只运行一个会话?
- html - 如何使用 Angular 10 在 html 中使下拉菜单可编辑
- omnet++ - 尝试运行 Omnet++ 模拟时出错