Skip to content Skip to sidebar Skip to footer

How To Overlay Data Points On A Barplot With A Categorical Axis

Goal: I am trying to show individual data points in a figure with multiple grouped bar charts using Seaborn. Problem: I tried to do it with a catplot for the bar chart and another

Solution 1:

  • seaborn.catplot is a figure-level plot, and they can't be combined.
  • As shown below, axes-level plots like seaborn.barplot and seaborn.stripplot can be plotted to the same axes.
import seaborn as sns

tips = sns.load_dataset("tips")

ax = sns.barplot(
    x="sex", 
    y="total_bill", 
    hue="smoker", 
    data=tips, 
    ci="sd", 
    edgecolor="black",
    errcolor="black",
    errwidth=1.5,
    capsize = 0.1,
    alpha=0.5
)

sns.stripplot(
    x="sex", 
    y="total_bill", 
    hue="smoker", 
    data=tips, dodge=True, alpha=0.6, ax=ax
)

# remove extra legend handles
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[2:], labels[2:], title='Smoker', bbox_to_anchor=(1, 1.02), loc='upper left')

enter image description here

Solution 2:

  • Figure-level plots (seaborn.catplot) may not be combined, however, it's possible to map an axes-level plot (seaborn.stripplot) onto a figure-level plot.
  • Tested in python 3.8.11, matplotlib 3.4.3, seaborn 0.11.2
import seaborn as sns

tips = sns.load_dataset("tips")

g = sns.catplot(
    x="sex", 
    y="total_bill", 
    hue="smoker", 
    row="time", 
    data=tips, 
    kind="bar", 
    ci = "sd", 
    edgecolor="black",
    errcolor="black",
    errwidth=1.5,
    capsize = 0.1,
    height=4, 
    aspect=.7,
    alpha=0.5)

# map data to stripplot
g.map(sns.stripplot, 'sex', 'total_bill', 'smoker', hue_order=['Yes', 'No'], order=['Male', 'Female'],
      palette=sns.color_palette(), dodge=True, alpha=0.6, ec='k', linewidth=1)

enter image description here

Post a Comment for "How To Overlay Data Points On A Barplot With A Categorical Axis"