Home > Enterprise >  Controlling the spacing between grouped bars in Seaborn
Controlling the spacing between grouped bars in Seaborn

Time:12-20

I am trying to add some space between bars. Here is an example of the bar chart that I want to modify,

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

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

age_plot = sns.barplot(data=df, x="Age", y="Name", hue="Gender")
plt.show()

Here is the output

I want to add some space between the M and F bars. Right now they are completely attached. I have searched and searched but haven't found a good solution. There was one solution that suggested to add an empty category but that does not work for my dataset.

CodePudding user response:

Using edgecolor and linewidth

One way to do this is via using linewidth and edgecolor parameters -

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

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

age_plot = sns.barplot(data=df, x="Age", y="Name", hue="Gender", linewidth=5, edgecolor='w')
plt.show()

enter image description here

Using set_width

Another way would be to use set_width over each of the patches in the plot.

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

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

age_plot = sns.barplot(data=df, x="Age", y="Name", hue="Gender")

for i in age_plot.patches:
  i.set_height(0.3)

plt.show()

enter image description here

  • Related