Matplotlib and Seaborn: A Practical Guide to Data Visualization in Python
Everything you actually need to learn, and the tools real teams use every day.
When students start learning Data Science and Machine Learning, they quickly discover that working with data is not only about writing code and calculating numbers.
We also need to understand and visualize the data.
A table of numbers can be difficult to understand, but a good chart can show a pattern immediately.
For example, instead of looking at this:
StudentMathScienceAli8085Sara6570Ahmed9088Ayesha7580John5560
we can create a graph that makes the differences much easier to see.
This is where Python visualization libraries become useful.
In this article, we will learn:
- What data visualization is
- Matplotlib
- Common Matplotlib charts
- Figure and Axes
- Seaborn
- Common Seaborn charts
- Correlation heatmaps
- Matplotlib vs Seaborn
- Other visualization libraries
- Which libraries students should learn first
What Is Data Visualization?
Data visualization means representing data using graphical elements such as charts, graphs, and plots.
Visualization helps us answer questions such as:
- Which value is highest?
- Which category is lowest?
- Is there a relationship between two variables?
- How is the data distributed?
- Are there unusual values?
- Is there a trend?
For example, if we have students’ marks, we can use a bar chart to compare their marks.
If we have house prices and house sizes, we can use a scatter plot to see whether larger houses tend to have higher prices.
This is especially important in Machine Learning, because we normally explore and understand our data before training a model.
The Two Main Libraries
Two of the most commonly used Python libraries for data visualization are:
- Matplotlib
- Seaborn
They are closely related, but they have different strengths.
Matplotlib is a general-purpose visualization library that gives us a lot of control over charts.
Seaborn provides a higher-level interface that makes many statistical visualizations easier to create.
A good learning approach is:
Learn Matplotlib first, then learn Seaborn.
1. Matplotlib
Matplotlib is one of the most important visualization libraries in the Python ecosystem.
We normally import its pyplot module like this:
import matplotlib.pyplot as pltWe use plt as a short name for matplotlib.pyplot.
Matplotlib can create many different types of charts, including:
- Line plots
- Bar charts
- Scatter plots
- Histograms
- Box plots
- Pie charts
- Subplots
- 3D plots
Creating Our Dataset
Before creating graphs, let’s create a small dataset.
We will use a Pandas DataFrame so that the examples are similar to what students will see when working with real datasets.
import pandas as pd
students = pd.DataFrame({
"name": ["Ali", "Sara", "Ahmed", "Ayesha", "John"],
"math": [80, 65, 90, 75, 55],
"science": [85, 70, 88, 80, 60],
"age": [18, 19, 18, 20, 19]
})
studentsThe DataFrame looks like this:
name math science age
0 Ali 80 85 18
1 Sara 65 70 19
2 Ahmed 90 88 18
3 Ayesha 75 80 20
4 John 55 60 19Now we can use this data to create different visualizations.
Line Plot
A line plot is useful when we want to show how values change across an ordered sequence.
import matplotlib.pyplot as plt
plt.plot(students["name"], students["math"])
plt.xlabel("Student")
plt.ylabel("Math Marks")
plt.title("Student Math Marks")
plt.show()Let’s understand the important parts.
plt.plot()Creates the line plot.
students["name"]Provides the values for the X-axis.
students["math"]Provides the values for the Y-axis.
plt.xlabel()Adds a label to the X-axis.
plt.ylabel()Adds a label to the Y-axis.
plt.title()Adds a title to the graph.
plt.show()Displays the graph.
Bar Chart
A bar chart is useful when we want to compare categories.
For example, we can compare the Math marks of our students.
plt.bar(students["name"], students["math"])
plt.xlabel("Student")
plt.ylabel("Math Marks")
plt.title("Math Marks by Student")
plt.show()A bar chart makes it easy to see:
- Ahmed has the highest Math marks.
- John has the lowest Math marks.
- The other students are between them.
Bar charts are commonly used for categorical comparisons.
Scatter Plot
A scatter plot is extremely important in Data Science and Machine Learning.
It helps us understand the relationship between two numerical variables.
For example, let’s compare Math and Science marks.
plt.scatter(students["math"], students["science"])
plt.xlabel("Math Marks")
plt.ylabel("Science Marks")
plt.title("Math vs Science")
plt.show()Here:
X-axis → Math marks
Y-axis → Science marksNow we can ask:
Do students who score higher in Math also tend to score higher in Science?
This type of question is important when learning about correlation and Machine Learning features.
Histogram
A histogram shows the distribution of numerical data.
For example:
plt.hist(students["math"], bins=5)
plt.xlabel("Math Marks")
plt.ylabel("Number of Students")
plt.title("Distribution of Math Marks")
plt.show()A histogram helps us understand where the values are concentrated.
For example, we might want to know:
Are most students scoring between 70 and 90?
A histogram can help answer this question.
What Does bins Mean?
In this code:
plt.hist(students["math"], bins=5)bins=5 means we divide the range of values into approximately five groups.
For example:
50–60
60–70
70–80
80–90
90–100The height of each bar tells us how many values fall into that range.
Box Plot
A box plot is useful for understanding the distribution and spread of data.
It can help us identify:
- Median
- Quartiles
- Spread
- Possible outliers
Example:
plt.boxplot(students["math"])
plt.ylabel("Math Marks")
plt.title("Distribution of Math Marks")
plt.show()Box plots become especially useful when students learn about statistics, outliers, and data preprocessing.
Multiple Plots with Matplotlib
Matplotlib allows us to create multiple plots inside one figure.
fig, ax = plt.subplots(1, 2)
ax[0].bar(students["name"], students["math"])
ax[0].set_title("Math Marks")
ax[1].bar(students["name"], students["science"])
ax[1].set_title("Science Marks")
plt.show()Here we have two important concepts:
Figure
figThe Figure is the complete area that contains our visualization.
Axes
axThe Axes are the individual plotting areas inside the figure.
In this example:
ax[0]represents the first plot.
ax[1]represents the second plot.
Students should understand this because they will see Figure and Axes frequently in more advanced Matplotlib code.
Important Matplotlib Functions
Students don’t need to memorize every Matplotlib function.
Start with these:
FunctionPurposeplt.plot()Line plotplt.bar()Bar chartplt.scatter()Scatter plotplt.hist()Histogramplt.boxplot()Box plotplt.xlabel()X-axis labelplt.ylabel()Y-axis labelplt.title()Chart titleplt.legend()Show legendplt.grid()Add gridplt.show()Display the chartplt.subplots()Create multiple plots
Once students understand these, they already have a strong foundation in Matplotlib.
2. Seaborn
Now let’s move to Seaborn.
We import it using:
import seaborn as snsSeaborn is built on top of Matplotlib and is designed especially for statistical data visualization.
One of its biggest advantages is that it works very naturally with Pandas DataFrames.
For example, instead of writing:
plt.scatter(students["math"], students["science"])we can write:
sns.scatterplot(
data=students,
x="math",
y="science"
)
plt.show()Here we directly tell Seaborn:
data = students
x = math
y = scienceThis becomes very convenient when working with larger datasets.
Seaborn Scatter Plot
Let’s create a scatter plot using Seaborn.
sns.scatterplot(
data=students,
x="math",
y="science"
)
plt.title("Math vs Science")
plt.show()This shows the relationship between Math and Science marks.
Using hue
One of Seaborn’s useful features is hue.
Let’s add another column to our dataset:
students["gender"] = [
"Male",
"Female",
"Male",
"Female",
"Male"
]Now we can use:
sns.scatterplot(
data=students,
x="math",
y="science",
hue="gender"
)
plt.title("Math vs Science by Gender")
plt.show()The hue parameter tells Seaborn to use different visual groups based on another column.
Get Mohammad Atif’s stories in your inbox
Join Medium for free to get updates from this writer.
In simple words:
huehelps us see another variable in the same graph.
This becomes very useful during Exploratory Data Analysis.
Seaborn Line Plot
We can also create line plots with Seaborn.
sns.lineplot(
data=students,
x="age",
y="math"
)
plt.title("Age vs Math Marks")
plt.show()Seaborn is particularly useful when our dataset contains repeated observations and we want statistical aggregation.
Seaborn Histogram
We can create a histogram using:
sns.histplot(
data=students,
x="math",
bins=5
)
plt.title("Distribution of Math Marks")
plt.show()This helps us understand the distribution of Math marks.
Seaborn Box Plot
We can create a box plot like this:
sns.boxplot(
data=students,
y="math"
)
plt.title("Math Marks Distribution")
plt.show()We can also compare different groups.
sns.boxplot(
data=students,
x="gender",
y="math"
)
plt.title("Math Marks by Gender")
plt.show()This allows us to compare the distribution of Math marks between groups.
Seaborn Regression Plot
This is particularly useful for students who are moving toward Machine Learning.
sns.regplot(
data=students,
x="math",
y="science"
)
plt.title("Math vs Science")
plt.show()A regression plot displays the data points along with a regression line.
This gives students a visual introduction to the idea behind Linear Regression.
Later, when they learn Machine Learning, they will understand the connection between the visualization and the regression model.
Correlation Heatmap
A correlation heatmap is one of the most useful visualizations in Data Science.
Let’s create one:
sns.heatmap(
students[["math", "science", "age"]].corr(),
annot=True
)
plt.title("Correlation Heatmap")
plt.show()The correlation value normally ranges from:
-1 → Strong negative relationship
0 → Little or no linear relationship
+1 → Strong positive relationshipFor example:
Math ↔ Science
0.95A value close to +1 means that the two variables have a strong positive linear relationship.
The heatmap makes these relationships easy to see.
Matplotlib vs Seaborn
So, what is the difference?
MatplotlibSeabornGeneral-purpose visualizationStatistical visualizationMore controlEasier statistical plotsOften requires more codeOften requires less codeHighly customizableGood default appearanceFoundation for many Python visualizationsBuilt on top of MatplotlibGood for detailed customizationExcellent for DataFrame-based analysis
A simple way to remember it is:
Matplotlib gives you more control, while Seaborn makes statistical visualization easier.
Should You Learn Matplotlib or Seaborn First?
I recommend:
Matplotlib
↓
Seaborn
↓
PlotlyWhy?
Because Seaborn uses Matplotlib underneath.
If students learn only Seaborn, they may be able to create beautiful graphs, but they may not understand what is happening when they need more control over the visualization.
Learning Matplotlib first gives them a stronger foundation.
Other Python Visualization Libraries
Matplotlib and Seaborn are not the only visualization libraries available.
There are many others, and students should at least know that they exist.
They don’t need to learn all of them immediately.
Plotly
Plotly is very useful for creating interactive visualizations.
For example:
import plotly.express as px
fig = px.scatter(
students,
x="math",
y="science",
color="gender"
)
fig.show()Plotly charts can provide interactive features such as:
- Hover information
- Zooming
- Panning
- Interactive filtering
- Interactive dashboards
When should you learn Plotly?
Learn Plotly when you want to build:
- Interactive charts
- Dashboards
- Data applications
- Web-based visualizations
Pandas Plotting
Pandas also provides simple plotting functionality.
For example:
students["math"].plot(kind="bar")Pandas uses Matplotlib for its plotting functionality.
This is useful when you want to quickly create a visualization directly from a DataFrame or Series.
Altair
Altair is another Python visualization library.
It follows a declarative approach.
Instead of manually describing every drawing step, you describe the relationship between your data and the visualization.
It is useful for:
- Statistical visualization
- Exploratory Data Analysis
- Clean and concise chart definitions
Students don’t need to learn it immediately, but it is worth knowing about.
Bokeh
Bokeh focuses on interactive visualizations that can be displayed in web browsers.
It can be useful for:
- Interactive charts
- Web applications
- Dashboards
Students who become interested in interactive web-based visualization can explore Bokeh later.
GeoPandas
If students work with geographical data, GeoPandas becomes useful.
For example:
Countries
Cities
Districts
Roads
Population
Geographical boundariesGeoPandas extends Pandas for working with geographic data.
It is useful for creating maps and analyzing location-based datasets.
Folium
Folium is useful for creating interactive maps using geographic data.
For example, students can use it to display:
- Cities
- Schools
- Hospitals
- Roads
- Business locations
- Geographic regions
It is a good library to explore if students are interested in maps and location-based applications.
Which Visualization Library Should Students Learn?
Students don’t need to learn every visualization library.
For a Data Science and Machine Learning path, I recommend:
First
MatplotlibLearn the fundamentals of visualization.
Second
SeabornLearn statistical visualization and Exploratory Data Analysis.
Third
PlotlyLearn interactive visualization.
After that, students can explore specialized libraries depending on their interests.
Interactive visualization → Plotly / BokehGeographical data → GeoPandas / FoliumDeclarative visualization → AltairQuick DataFrame charts → Pandas plotting
A Simple Visualization Roadmap
Students can follow this path:
Data Visualization
|
┌───────────┴───────────┐
↓ ↓
Matplotlib Seaborn
Foundation Statistical plots
|
↓
Plotly
Interactive charts
|
┌──────┼─────────┐
↓ ↓ ↓
Altair Bokeh GeoPandas
|
Folium
Which Chart Should I Use?
One of the most important things students should learn is not just how to create a chart, but when to use a particular chart.
Here is a simple way to choose the right visualization:
1. How does something change over time or across an ordered sequence?
Use a Line Plot.
2. Which category is larger or smaller?
Use a Bar Chart.
3. Are two numerical variables related?
Use a Scatter Plot.
4. How are numerical values distributed?
Use a Histogram.
5. Are there possible outliers in the data?
Use a Box Plot.
6. How strongly are different numerical variables related?
Use a Correlation Heatmap.
7. Do I want to show a relationship with a trend line?
Use a Regression Plot.
8. Do I need an interactive visualization?
Use Plotly.
The important lesson is that students should not simply memorize visualization functions. They should first understand the question they want to answer, and then choose the chart that best answers that question.
Choose the visualization based on the question, not just on how the chart looks.
A Practical Data Science Example
Imagine we have a house-price dataset.
It contains:
size
bedrooms
location
age
priceBefore training a Machine Learning model, we might visualize the data.
Question 1
Does house size have a relationship with price?
Use:
sns.scatterplot(data=df, x="size", y="price")Question 2
What is the distribution of house prices?
Use:
sns.histplot(data=df, x="price")Question 3
Are there extreme house prices?
Use:
sns.boxplot(data=df, y="price")Question 4
Which numerical variables are correlated?
Use:
sns.heatmap(df.corr(), annot=True)This is how visualization becomes part of a real Machine Learning workflow.
Final Learning Path
For students who want to become Data Scientists or Machine Learning Engineers, I recommend this order:
Python
↓
NumPy
↓
Pandas
↓
Matplotlib
↓
Seaborn
↓
Exploratory Data Analysis
↓
Statistics
↓
Data Preprocessing
↓
Machine LearningThen later:
Machine Learning
↓
Deep Learning
↓
PyTorch / TensorFlow
↓
Computer Vision / NLPAnd for visualization:
Matplotlib
↓
Seaborn
↓
Plotly
↓
Specialized librariesFinal Thoughts
Students should not think of visualization as simply learning commands such as:
plt.plot()
sns.scatterplot()
sns.heatmap()The real skill is understanding why and when to use each visualization.
The most important question should always be:
What question am I trying to answer with my data?
Once students understand that, choosing the right visualization becomes much easier.
If you are learning Data Science, start with Matplotlib, move to Seaborn, and then explore Plotly when you need interactive visualizations.
You don't need to learn every visualization library.
If you only learn three, start with:
1. Matplotlib
2. Seaborn
3. PlotlyThese three provide a strong foundation for most beginner-to-intermediate Data Science and Machine Learning visualization work.








