-1

Is there a way to separate the bars of different levels of the categorial variable (hue = "Session") with a blank space?

As you can see, I did this grouped barplot with seaborn, but the bars for each level of the variable "Session" are all attached.

How can I add a blank space?

I attached a similar graph done with ggplot in R. I want to obtein a similar result but with seaborn on another python library.

Seaborn Barplot

ggplot example

Here the snipped code:

desired_order = ["Ignored Visual Field","Attended Visual Field","Control"]

custom_palette = ["#A2142F", "#20B2AA", "#D95319"]
my_file_sham = my_file[my_file["Stimulation"]=="Sham"]

my_file_sham["Response_scaled"] = (my_file_sham["Response"]) * 100


fig_5 = sns.barplot(data=my_file_sham, x="Manipulation", y="Response_scaled", hue="Session", order= desired_order, palette=custom_palette, linewidth=3)

pal = ["#A2142F", "#20B2AA", "#D95319"]
color = pal * df.shape[1]

for p,c in zip(fig_5.patches,color):
    p.set_color(c)
    
plt.show()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Mik
  • 1
  • 2
  • 1
    `g= sns.catplot(kind='bar', data=my_file_sham, col="Manipulation", x="Manipulation", y="Response_scaled", hue="Session", col_order= desired_order`, sharex=False)` could be seaborn way. Please note that your post is missing reproducible test data. Also note that `sns.barplot` returns an `ax`, not a figure (see e.g. [this post](https://stackoverflow.com/questions/66410803/understanding-of-fig-ax-and-plt-when-combining-matplotlib-and-pandas) to better grasp the difference). – JohanC Aug 15 '23 at 14:02
  • 1
    I think it looks cleaner, and it's certainly easier to just add `ec='k'` to the plot call – Trenton McKinney Aug 15 '23 at 16:18

1 Answers1

0

There is no built-in way to do this with seaborn but you can take a more manual approach.

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
tips = sns.load_dataset("tips")

# Create the barplot using Seaborn
g = sns.barplot(data=tips, x="day", y="total_bill", hue="sex", ci=None)
ax = g.axes

# Get the bars
bars = ax.patches

# Define the space between the grouped bars
space_between_groups = 0.2

# Define the space between the bars within the group
space_within_groups = 0.05

# Iterate through the bars and set new positions
for i, bar in enumerate(bars):
    new_x = i // 2 * (space_between_groups + 2 * bar.get_width()) + (i % 2) * (bar.get_width() + space_within_groups)
    bar.set_x(new_x)

# Set the new x-ticks
new_ticks = [i * (space_between_groups + 2 * bar.get_width()) + bar.get_width() for i in range(len(tips['day'].unique()))]
ax.set_xticks(new_ticks)
ax.set_xticklabels(tips['day'].unique())

plt.show()
JJenkins
  • 81
  • 6