Seaborn β Declarative Visualization
After completing this topic
You will understand how Seaborn's declarative syntax differs from Matplotlib, and you will be able to draw box plots, count plots, and heatmaps with a single line of code.
When Matplotlib Becomes Inconvenient
To draw a "salary distribution by department" using Matplotlib, you would write code like this:
import matplotlib.pyplot as pltimport numpy as np
departments = df['department'].unique()positions = range(len(departments))
fig, ax = plt.subplots()for i, dept in enumerate(departments): salaries = df[df['department'] == dept]['salary'] ax.boxplot(salaries, positions=[i], widths=0.6)
ax.set_xticks(positions)ax.set_xticklabels(departments)ax.set_ylabel('Salary')ax.set_title('Salary Distribution by Department')plt.show()You have to loop, separate the data, calculate positions, and set labels directly. With Seaborn, the same graph is:
import seaborn as sns
sns.boxplot(data=df, x='department', y='salary')plt.show()Just two lines. You just say "what to show," and Seaborn handles the rest. This is declarative syntax.
Imperative vs. Declarative
| Matplotlib (Imperative) | Seaborn (Declarative) | |
|---|---|---|
| Perspective | Step-by-step instructions on "how to draw" | Declaration of "what to show" |
| Data Separation | Manual looping/filtering | Automatic (x, y, hue) |
| Colors/Legends | Manual specification | Automatic generation |
| Customization | Highly detailed | Mostly automatic; detailed customization with Matplotlib |
Seaborn is a wrapper built on top of Matplotlib. It creates beautiful graphs quickly with default settings, and if you need fine-tuning, you can go down to Matplotlib.
5 Core Graphs
1. Distribution β histplot
sns.histplot(data=df, x='salary', bins=20, kde=True)Adding kde=True overlays a density estimate line (smooth curve).
2. Distribution by Category β boxplot
sns.boxplot(data=df, x='department', y='salary')See median, quartiles, and outliers at a glance. Most effective for comparing salaries between departments.
3. Counting β countplot
sns.countplot(data=df, x='department', hue='gender')Shows the frequency of each category with bars. Adding a subcategory, such as gender, with hue separates it by color.
4. Relationship β scatterplot
sns.scatterplot(data=df, x='experience', y='salary', hue='department')Plots the relationship between two numerical variables as points. At a glance, you can see whether experience and salary are proportional.
5. Correlation β heatmap
corr = df[['salary', 'experience', 'age']].corr()sns.heatmap(corr, annot=True, cmap='coolwarm', vmin=-1, vmax=1)Display the numbers with annot=True and specify the color palette with cmap. Positive correlation (red) and negative correlation (blue) are distinguished by color.
hue β The Third Variable
Seaborn's most powerful feature:
# Without hue β overall scatter plotsns.scatterplot(data=df, x='experience', y='salary')
# Add hue β separate by color for each departmentsns.scatterplot(data=df, x='experience', y='salary', hue='department')hue encodes the third variable with color. To do this with Matplotlib, you would have to loop and specify the colors directly. Seaborn only needs one word.
Style Settings
# Change the overall stylesns.set_theme(style='whitegrid')
# Change the palettesns.set_palette('Set2')
# For individual graphssns.boxplot(data=df, x='dept', y='salary', palette='pastel')Style options:
darkgridβ default, gray background + gridwhitegridβ white background + griddarkβ gray background without gridwhiteβ clean white backgroundticksβ only axis ticks
Seaborn + Matplotlib Combination
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
sns.boxplot(data=df, x='dept', y='salary', ax=axes[0])axes[0].set_title('Salary by Department')
sns.histplot(data=df, x='salary', bins=20, ax=axes[1])axes[1].set_title('Overall Salary Distribution')
plt.tight_layout()plt.show()You can put Seaborn graphs into Matplotlib's Axes using the ax parameter. Layout with Matplotlib, graph content with Seaborn β this combination is a practical pattern.
Key Takeaway
Seaborn is a visualization library that you simply declare "what to show," and it will draw the rest. Encoding the third variable with color with just one word,
hueβ this is Seaborn's core strength. Quick exploration with Seaborn, fine-tuning with Matplotlib β you need to know how to use both.