Seaborn
Seaborn is a library built on top of Matplotlib that makes attractive statistical charts with very little code. It works directly with pandas DataFrames: you name the columns, and seaborn handles grouping, colours, legends and summary statistics.
Getting started
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid") # a clean default look for every chart
orders = pd.DataFrame({
"county": ["Nairobi", "Nairobi", "Nairobi", "Kisumu", "Kisumu",
"Kisumu", "Nakuru", "Nakuru", "Nakuru"],
"channel": ["Shop", "M-Pesa", "M-Pesa", "Shop", "M-Pesa",
"Shop", "Shop", "M-Pesa", "M-Pesa"],
"amount": [1200, 1850, 2400, 900, 1300, 1100, 700, 1500, 1650], # KES
})
Seaborn works best with tidy (long-format) data: one row per observation and one column per variable, exactly like orders. Every seaborn function takes data= plus column names for x, y and, optionally, hue (colour by group).
Bar plots: averages by group
ax = sns.barplot(data=orders, x="county", y="amount", hue="channel", errorbar=None)
ax.set_title("Average order by county and payment channel")
ax.set_ylabel("Average order (KES)")
plt.show()
What the chart shows: two coloured bars for each county, one per channel, with a legend. The bar heights are the average order:
| County | Shop | M-Pesa |
|---|---|---|
| Nairobi | 1200 | 2125 |
| Kisumu | 1000 | 1300 |
| Nakuru | 700 | 1575 |
In every county, M-Pesa orders are larger on average than in-shop orders.
hue="channel". Each bar is a group mean; seaborn picks its own colours.sns.barplot() shows the mean of each group by default, not the total. If you want totals, pass estimator="sum". By default it also draws a black error bar showing a 95% confidence interval (calculated by resampling, so it can vary slightly between runs); errorbar=None hides it. To show how many rows are in each group, use sns.countplot() instead.
Box plots: comparing distributions
ax = sns.boxplot(data=orders, x="channel", y="amount")
ax.set_title("Order size by payment channel")
plt.show()
What the chart shows: one box per channel. The line inside each box is the median: KES 1,000 for Shop orders (the middle of 700, 900, 1100 and 1200) and KES 1,650 for M-Pesa orders. The box covers the middle half of the values (the interquartile range, or IQR), and the "whiskers" reach out to the most extreme values that are not unusually far from the box. A value more than 1.5 × IQR beyond the edge of the box is drawn as a separate dot (an outlier). Here the M-Pesa box runs from 1,500 to 1,850, so the KES 2,400 order lies just past the cut-off of 2,375 and appears as a dot. Box plots compare the spread and centre of several groups in one glance. See Descriptive Statistics for medians and quartiles.
Histograms and density curves
ax = sns.histplot(data=orders, x="amount", bins=4, kde=True)
ax.set_xlabel("Order value (KES)")
plt.show()
What the chart shows: four bars counting how many orders fall in each range between KES 700 and 2,400, plus a smooth curve (a kernel density estimate) tracing the overall shape of the distribution. Add hue="channel" to overlay one histogram per channel in different colours.
Scatter and line plots
weather = pd.DataFrame({
"temp_c": [20, 22, 25, 27, 30, 32],
"sodas_sold": [110, 125, 120, 150, 160, 175],
})
ax = sns.scatterplot(data=weather, x="temp_c", y="sodas_sold", s=80)
sns.regplot(data=weather, x="temp_c", y="sodas_sold", scatter=False, ax=ax)
plt.show()
What the chart shows: six dots rising from left to right, with a straight best-fit line through them and a shaded band showing the uncertainty around that line. sns.lineplot() works the same way for data over time; if several rows share the same x value, it draws their mean with a shaded band.
Heatmaps
A heatmap colours each cell of a table by its value. Its most common use is to show a correlation matrix:
corr = weather.corr()
ax = sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", vmin=-1, vmax=1)
ax.set_title("Correlation between temperature and soda sales")
plt.show()
What the chart shows: a 2 × 2 grid. The two diagonal cells read 1.00 (each variable compared with itself) and the two off-diagonal cells read 0.95, coloured deep red for a strong positive relationship. Fixing vmin=-1 and vmax=1 keeps the colour scale honest, so blue always means negative and red positive.
Figure-level functions
The functions above draw onto one Matplotlib Axes. Seaborn also has figure-level functions that can split data into a grid of small charts using col= and row=:
| Figure-level | Same family as |
|---|---|
sns.relplot() | scatterplot(), lineplot() |
sns.displot() | histplot(), kdeplot() |
sns.catplot() | barplot(), boxplot(), countplot() |
sns.catplot(data=orders, x="channel", y="amount", col="county", kind="bar", errorbar=None) plt.show()
What the figure shows: three small bar charts side by side, one per county, each comparing Shop and M-Pesa averages on the same y-axis scale.
Seaborn charts are Matplotlib charts underneath, so everything from Matplotlib Basics still works: ax.set_title(), ax.set_ylabel(), fig.savefig(). For readers with colour-vision differences, try sns.set_theme(palette="colorblind").
Key points
- Seaborn makes statistical charts from DataFrames: pass
data=,x=,y=and optionallyhue=. barplot()shows group means by default; useestimator="sum"for totals.boxplot()andhistplot()show distributions;heatmap()shows tables of values such as correlations.- Use figure-level functions (
relplot,displot,catplot) for grids of small charts.
Tip: use the ← and → keys to move between pages.
