Learning path: Explore a Dataset Before You Model · Step 2 of 6
Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
Look at one column at a time: read the peak and the tail of a histogram, compare groups with hue, count categories, and tame a long tail with log1p. Shown on restaurant bills and iris flowers.
What you will learn
- Draw a histogram with sns.histplot and read its peak and tail
- Spot right skew by comparing the mean and the median
- Compare groups with kdeplot and hue to rank features
- Count a category column with countplot and pull in a long tail with np.log1p
Before you start
- Reading a CSV with pandas
- First Look at a Dataset
Picture a class of students lining up by height. Short ones on the left, tall ones on the right, and students of the same height stand in one column. The tallest column is the peak: most students stand there. On the right, a few taller ones thin out. That long thin side is the tail.
A histogram is exactly this line-up, drawn for a column of numbers. Looking at one column on its own like this is called univariate analysis, and it tells you a lot about your data before any model sees it. Let's do it on two small datasets: 244 restaurant bills (tips) and 150 iris flowers.
If you haven't run the basic health checks on a dataset yet, start with First Look at a Dataset.
Load the data
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
tips = pd.read_csv("tips.csv")
iris = pd.read_csv("iris.csv")
A number column: the histogram
sns.histplot(data=tips, x="total_bill", bins=20)
plt.show()

Here's what happens inside. bins=20 cuts the range of bills into twenty slots. Every one of the 244 bills drops into its slot, and each bar's height is how many bills fell in. In this plot the tallest bar holds 37 bills, and the tall bars sit between 10 and 20 dollars: more than half of all bills are in that range.
Read the shape with three numbers
Looking at a plot is good. Reading it with numbers is better.
bill = tips["total_bill"]
print("mean ", bill.mean().round(2))
print("median", bill.median())
print("max ", bill.max())
mean 19.79
median 17.795
max 50.81
On the right of the histogram there's a long tail of a few big bills, up to 50.81. The median (17.795, the middle bill) sits close to the peak. The mean (19.79) is higher, because those few big bills pull the average to the right.
Rule of thumb: when the mean is bigger than the median, the long tail is on the right. That's called right skew, and it's worth spotting early.
A smooth curve on top: kde=True
sns.histplot(data=tips, x="total_bill",
bins=20, kde=True)
plt.show()
The same histogram, now with a smooth density curve (a KDE) drawn over the bars. It shows the shape without the jagged edges, and the peak and the tail are still there.
One thing to watch: the bins value changes the look. Too few bins hide the shape, too many look noisy. Trying a couple of values is a good habit.
Compare groups with hue
kdeplot draws just the smooth curve, fill=True colours under it, and hue="species" gives one curve per species.
sns.kdeplot(data=iris, x="petal_length",
hue="species", fill=True)
plt.show()

Setosa sits completely on its own, far to the left. Versicolor and virginica overlap only a little. So petal length alone already tells the species apart. That's a strong feature.
Now change only the column name:
sns.kdeplot(data=iris, x="sepal_width",
hue="species", fill=True)
plt.show()

This time the three curves pile on top of each other. Knowing the sepal width tells you very little about the species. It's a weak feature. With one quick plot per column, you can already rank your features. That's what exploring is for.
A category column: count it
Text has no shape, so we count it. countplot draws one bar per category, and order puts the days in calendar order.
sns.countplot(data=tips, x="day",
order=["Thur", "Fri", "Sat", "Sun"])
plt.show()
The same counts as numbers:
tips["day"].value_counts()
day
Sat 87
Sun 76
Thur 62
Fri 19
Name: count, dtype: int64
Saturday is the busiest day with 87 bills. Friday has only 19, so any pattern you find for Fridays rests on very little data.
One plot per group: displot with col
Say you want the same histogram for each group. displot with col="time" draws one panel for each value of time. height only sets the size.
sns.displot(data=tips, x="total_bill",
col="time", bins=15, height=3.2)
plt.show()
tips["time"].value_counts()
time
Dinner 176
Lunch 68
Name: count, dtype: int64
Two histograms side by side, from one line. Both lean to the right, and dinner (176 bills) has a longer tail of big bills than lunch (68).
Taming a long tail with log1p
You can read a long tail. But some models, linear ones especially, learn better when a column isn't so lopsided. A common fix is np.log1p, the log of one plus the value.
import numpy as np
log_bill = np.log1p(bill)
print("skew before", bill.skew().round(2))
print("skew after ", log_bill.skew().round(2))
skew before 1.13
skew after -0.01
Skew drops from 1.13 to almost zero. Here's why it works. Take three bills:
| Bill | Dollars | log1p |
|---|---|---|
| Smallest | 3.07 | 1.40 |
| Median | 17.795 | 2.93 |
| Biggest | 50.81 | 3.95 |
The gap between the top two was about 33 dollars. After the log it's about 1. Big values shrink much more than small ones, so the long tail pulls in. The biggest bill is still the biggest, only squeezed.
sns.histplot(x=log_bill, bins=20)
plt.show()
In this histogram the peak now sits in the middle and the long tail is gone.
We apply transforms like this in preprocessing, on the training data only. More on that in Train-Test Split and Data Leakage.
Common mistakes
- Trusting one bins value. Try a couple; the shape can change.
- Reporting only the mean of a skewed column. Show the median too. Here they differ by two dollars.
- Drawing a histogram of a text column. Count categories with
countplotorvalue_counts(). - Ignoring small groups. 19 Friday bills is not much evidence for anything.
Quick recap
| Tool | What it shows | In this lesson |
|---|---|---|
histplot | One number column as bars | Bills peak at $10-20, long right tail |
kde=True | The smooth shape | Same peak and tail, no jagged edges |
hue | One curve per group | Petal length separates setosa; sepal width doesn't |
countplot | Counts of a category | Sat 87, Sun 76, Thur 62, Fri 19 |
displot(col=...) | One plot per group | Dinner 176, Lunch 68 |
np.log1p | Pulls in a long tail | Skew 1.13 to -0.01 |
Next, look at two columns at a time in Scatter Plots and Pair Plots.
Try it yourself
Draw a histogram of the tip column. Which side is the long tail on? Check your answer by comparing the mean and the median.
The notebook and both datasets are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →First Look at a Dataset: 6 Checks Before You Plot or Model
Next →Scatter Plots and Pair Plots: See How Two Columns Relate
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
First Look at a Dataset: 6 Checks Before You Plot or Model
Six quick pandas checks that tell you what's inside a dataset: size, types, gaps, spread, label balance and duplicates. Shown on 142,193 days of Australian weather.
Scatter Plots and Pair Plots: See How Two Columns Relate
Draw one dot per row with seaborn scatterplot, colour the dots by group with hue, turn a clean split into a one-line rule, and read every pair at once with pairplot. Shown on iris and tips.
Finding Outliers: Box Plots, Violin Plots and the IQR Rule
Read a box plot from its five numbers, flag outliers with the 1.5 x IQR rule in pandas, compare groups with box and violin plots, and cap extreme values with clip. Shown on 244 restaurant bills.
Correlation and Heatmaps: Covariance, df.corr() and What They Miss
Put one number on "these two columns move together": why covariance depends on units, how correlation fixes it, scanning every pair with df.corr() and a seaborn heatmap, and the two traps correlation can't see.