How to control white space between bars in seaborn bar plots?

Viewed 10407

I have following simple example dataframe:

import pandas as pd
data = [['Alex',25],['Bob',34],['Sofia',26],["Claire",35]]
df = pd.DataFrame(data,columns=['Name','Age'])
df["sex"]=["male","male","female","female"]

I use following code to plot barplots:

import matplotlib.pyplot as plt

import seaborn as sns

age_plot=sns.barplot(data=df,x="Name",y="Age", hue="sex",dodge=False)
age_plot.get_legend().remove()
plt.setp(age_plot.get_xticklabels(), rotation=90)
plt.ylim(0,40)
age_plot.tick_params(labelsize=14)
age_plot.set_ylabel("Age",fontsize=15)
age_plot.set_xlabel("",fontsize=1)
plt.tight_layout()

Produces following bar plot:

enter image description here

My question: how can I control de whitespace between bars? I want some extra white space between the male (blue) and female (orange) bars.

Output should look like this (poorly edited in MS PPT):

enter image description here

I have found several topics on this for matplotplib (e.g.https://python-graph-gallery.com/5-control-width-and-space-in-barplots/) but not for seaborn. I'd prefer to use seaborn because of the easy functionality to color by hue.

Thanks.

1 Answers

A possibility is to insert an empty bar in the middle:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({'Name': ['Alex', 'Bob', 'Sofia', 'Claire'], 'Age': [15, 18, 16, 22], 'Gender': ['M', 'M', 'F', 'F']})
df = pd.concat([df[df.Gender == 'M'], pd.DataFrame({'Name': [''], 'Age': [0], 'Gender': ['M']}), df[df.Gender == 'F']])

age_plot = sns.barplot(data=df, x="Name", y="Age", hue="Gender", dodge=False)
age_plot.get_legend().remove()
plt.setp(age_plot.get_xticklabels(), rotation=90)
plt.ylim(0, 40)
age_plot.tick_params(labelsize=14)
age_plot.tick_params(length=0, axis='x')
age_plot.set_ylabel("Age", fontsize=15)
age_plot.set_xlabel("", fontsize=1)
plt.tight_layout()
plt.show()

example plot

Related