Seaborn Statistical Estimation & Data Handling
๐จ The core semantic mappings
sns.scatterplot(data=df, x="x", y="y", hue="category", size="value", style="group")| Param | Maps a variable to | Works with |
|---|---|---|
hue= | color | most plot types |
size= | point/line size or width | scatter, line |
style= | marker shape / line dashes | scatter, line |
hue+styletogether on the same variable = redundant encoding (color AND shape both show the category) โ genuinely helpful for colorblind accessibility or grayscale printing.
๐ Confidence intervals / error bars
sns.lineplot(data=df, x="x", y="y", errorbar="sd") # standard deviation
sns.lineplot(data=df, x="x", y="y", errorbar=("ci", 95)) # confidence interval, 95%
sns.lineplot(data=df, x="x", y="y", errorbar=("pi", 50)) # percentile interval
sns.lineplot(data=df, x="x", y="y", errorbar=None) # no error band at all
sns.barplot(data=df, x="cat", y="y", errorbar="se") # standard errorSeaborn computes these automatically via bootstrapping when there are multiple y-values per x. This is the main thing that separates Seaborn's
lineplot/barplotfrom plain matplotlib equivalents.
๐งฎ estimator โ how repeated values get aggregated
sns.barplot(data=df, x="day", y="total_bill", estimator="mean") # default
sns.barplot(data=df, x="day", y="total_bill", estimator="median")
sns.barplot(data=df, x="day", y="total_bill", estimator="sum")
sns.barplot(data=df, x="day", y="total_bill", estimator=len) # count๐ Long vs wide format data
# WIDE format โ one column per category
# Male Female
# 0 23 25
# 1 19 22
# LONG format โ one row per observation, category as a value
# sex value
# 0 Male 23
# 1 Female 25wide_to_long = df.melt(id_vars="id", var_name="sex", value_name="value") # pandas: wide โ longSeaborn generally expects LONG format (
x=,y=,hue=as column names). Most real-world CSVs come wide โdf.melt()is the standard fix.
sns.boxplot(data=long_df, x="sex", y="value") # works cleanly on long data๐งพ Handling missing data
sns.scatterplot(data=df.dropna(subset=["x", "y"]), x="x", y="y") # drop NaNs before plottingSeaborn generally silently drops NaN rows for the relevant columns rather than erroring โ good to know when a plot has fewer points than expected.
๐ข Ordering categories explicitly
sns.boxplot(data=df, x="day", y="total_bill", order=["Thur", "Fri", "Sat", "Sun"])
sns.barplot(data=df, x="day", y="total_bill", hue="sex", hue_order=["Male", "Female"])Without
order=, category axis order is whatever pandas/Seaborn infers (often alphabetical) โ explicitly set it whenever a natural order (days, sizes, ratings) matters.
๐ Related
Seaborn Categorical Plots ยท Seaborn Relational Plots ยท Seaborn