Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 01

What Is Seaborn

Meet Seaborn, the statistical plotting library built on Matplotlib: import it as sns, hand it a DataFrame and column names, and get a labelled chart.

Intermediate25 min
What Is Seaborn hero Module 26 Lesson 1What Is Seaborn hero Module 26 Lesson 1

Seaborn is a plotting library built on top of Matplotlib. Matplotlib asks you for lists of x and y values and styles each line by hand. Seaborn takes a whole pandas DataFrame plus the names of the columns you care about, then works out the groups, colours, legend, and axis labels itself. It is made for statistical questions: how groups compare, how values are spread, and how two measurements move together.

The path from a DataFrame through a Seaborn function to a Matplotlib chartThe path from a DataFrame through a Seaborn function to a Matplotlib chart

Import it as sns

Everyone imports Seaborn as sns, the same way pandas becomes pd. Seaborn still draws with Matplotlib underneath, so you keep importing matplotlib.pyplot as plt for plt.show(), titles, and saving.

python
import matplotlib.pyplot as plt
import seaborn as sns

print(sns.__version__)
print([name for name in ["scatterplot", "histplot", "boxplot", "heatmap"] if hasattr(sns, name)])

Output:

text
0.13.2
['scatterplot', 'histplot', 'boxplot', 'heatmap']

Seaborn is not built into this page's playground, so the first run that imports it downloads the library. That takes a few seconds; later runs are quick.

The table used in this module

Every lesson plots the same invented table of 120 learners. track is the course, mode is online or classroom, week runs from 1 to 6, hours is time studied that week, and score is that week's quiz result. The fixed random seed means you get exactly the same rows.

python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

rng = np.random.default_rng(26)
study = pd.DataFrame({
    "track": rng.choice(["Python", "Data", "Web"], 120),
    "mode": rng.choice(["online", "classroom"], 120),
    "week": rng.integers(1, 7, 120),
})
study["hours"] = (rng.uniform(1, 6, 120) + study["week"] * 0.8).round(1)
study["score"] = (35 + study["hours"] * 4.5 + rng.normal(0, 7, 120)).clip(0, 100).round()

print(study.head())
print(study.shape)

Output:

text
    track       mode  week  hours  score
0     Web  classroom     3    7.3   67.0
1    Data  classroom     4    5.4   60.0
2    Data     online     5    8.2   68.0
3  Python     online     3    7.3   67.0
4    Data     online     5    5.8   63.0
(120, 5)

One line, one chart

Pass the table as data= and name the columns for x and y. Seaborn reads the values, draws the dots, and labels both axes from the column names. The function returns the Matplotlib Axes it drew on.

python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

rng = np.random.default_rng(26)
study = pd.DataFrame({
    "track": rng.choice(["Python", "Data", "Web"], 120),
    "mode": rng.choice(["online", "classroom"], 120),
    "week": rng.integers(1, 7, 120),
})
study["hours"] = (rng.uniform(1, 6, 120) + study["week"] * 0.8).round(1)
study["score"] = (35 + study["hours"] * 4.5 + rng.normal(0, 7, 120)).clip(0, 100).round()

ax = sns.scatterplot(data=study, x="hours", y="score")
plt.show()

print(type(ax).__name__)
print(ax.get_xlabel(), "|", ax.get_ylabel())

Output:

text
Axes
hours | score

Groups without a loop

Colouring by track in plain Matplotlib means grouping the rows, looping over the groups, and building the legend yourself. In Seaborn it is one argument: hue="track". The two panels below draw the same picture.

python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

rng = np.random.default_rng(26)
study = pd.DataFrame({
    "track": rng.choice(["Python", "Data", "Web"], 120),
    "mode": rng.choice(["online", "classroom"], 120),
    "week": rng.integers(1, 7, 120),
})
study["hours"] = (rng.uniform(1, 6, 120) + study["week"] * 0.8).round(1)
study["score"] = (35 + study["hours"] * 4.5 + rng.normal(0, 7, 120)).clip(0, 100).round()

fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4), sharey=True)

for name, group in study.groupby("track"):
    left.scatter(group["hours"], group["score"], label=name, s=18)
left.legend()
left.set_title("Matplotlib: a loop per group")

sns.scatterplot(data=study, x="hours", y="score", hue="track", ax=right)
right.set_title("Seaborn: hue=\"track\"")
plt.show()

print([text.get_text() for text in right.get_legend().get_texts()])

Output:

text
['Web', 'Data', 'Python']

ax=right tells Seaborn which Matplotlib area to draw into, which is how Seaborn charts join ordinary subplots.

A theme for every chart

sns.set_theme() switches Matplotlib to Seaborn's look: a soft grid, a clearer font size, and a friendlier colour cycle. It changes every chart drawn after it, including plain Matplotlib ones.

python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

rng = np.random.default_rng(26)
study = pd.DataFrame({
    "track": rng.choice(["Python", "Data", "Web"], 120),
    "mode": rng.choice(["online", "classroom"], 120),
    "week": rng.integers(1, 7, 120),
})
study["hours"] = (rng.uniform(1, 6, 120) + study["week"] * 0.8).round(1)
study["score"] = (35 + study["hours"] * 4.5 + rng.normal(0, 7, 120)).clip(0, 100).round()

sns.set_theme(style="whitegrid")
sns.histplot(data=study, x="score")
plt.show()

print(plt.rcParams["axes.grid"])

Output:

text
True

Key takeaways

  • Seaborn builds statistical charts on top of Matplotlib

  • Pass a DataFrame as data= and name the columns for x, y, and hue

  • Axes-level functions return the Matplotlib Axes they drew on

  • sns.set_theme() restyles every chart drawn afterwards

  • Next: Tidy Data for Seaborn

  • Previous: Saving Figures

Loading playground…

Check your understanding

What Is Seaborn Quiz

What is Seaborn built on?

1 / 10