Seaborn条形图条之间没有空格

时间:2019-12-27 23:34:05

标签: python matplotlib seaborn

我使用下面的代码创建了一个Seaborn条形图(它来自https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/

我希望所有栏都没有空格而堆积,但一直无法做到。如果我添加宽度,它会抱怨barh中有多个width值。这可能是因为seaborn有自己的算法来确定宽度。反正周围吗?

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()

enter image description here

1 个答案:

答案 0 :(得分:2)

无论如何都不是matplotlib专家,因此可能会有更好的方法。也许您可以执行类似以下的操作,类似于this answer中的方法:

# 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)

enter image description here