Data Visualization with Matplotlib
(using Pandas DataFrames)
Complete Study Notes — Concept Revision + AI Engineer Interview Prep
1. What Is Data Visualization? ................................................................................................................................................. 3
2. Introduction to Matplotlib .................................................................................................................................................... 3
Why Matplotlib is powerful .................................................................................................................................................. 3
Two Ways to Plot in Matplotlib ............................................................................................................................................ 3
3. Anatomy of a Matplotlib Figure ........................................................................................................................................... 3
4. Installation & Import ............................................................................................................................................................ 4
Minimal Example................................................................................................................................................................... 4
5. Univariate vs Bivariate vs Multivariate Analysis ................................................................................................................ 4
6. Univariate Analysis ................................................................................................................................................................ 4
6.1 Single Numerical Column ............................................................................................................................................... 4
Line Plot.............................................................................................................................................................................. 4
Histogram ........................................................................................................................................................................... 4
Box Plot (Box-and-Whisker) ............................................................................................................................................. 5
6.2 Single Categorical Column.............................................................................................................................................. 5
Pie Chart ............................................................................................................................................................................. 5
Bar / Count Plot ................................................................................................................................................................. 5
7. Bivariate Analysis .................................................................................................................................................................. 5
7.1 Numerical vs Numerical .................................................................................................................................................. 6
Scatter Plot ......................................................................................................................................................................... 6
Line Plot (sorted) ............................................................................................................................................................... 6
Bar Plot ............................................................................................................................................................................... 6
7.2 Numerical vs Categorical ................................................................................................................................................ 6
Box Plot (grouped by category) ........................................................................................................................................ 6
Pie Chart (aggregated) ...................................................................................................................................................... 6
Bar Plot (mean per category) ............................................................................................................................................ 6
8. Multivariate Analysis ............................................................................................................................................................ 7
8.1 Three Numerical Columns → Bubble Plot .................................................................................................................... 7
8.2 Two Numerical + One Categorical → Color-Coded Scatter ........................................................................................ 7
8.3 Multiple Numerical Columns vs One Shared X → Multi-Line Plot ............................................................................ 7
9. Object-Oriented API — Subplots......................................................................................................................................... 7
10. Saving Figures ...................................................................................................................................................................... 8
11. 3D Plots ................................................................................................................................................................................. 8
Matplotlib 3D (best in VS Code / Jupyter — limited interactivity in Colab) ............................................................... 8
Plotly (fully interactive — works well in Colab) ............................................................................................................. 8
12. Quick Reference — "Which Plot Do I Use?" .................................................................................................................... 8
13. Interview Prep — Key Concepts & Sample Q&A ............................................................................................................ 9
13.1 Core Conceptual Questions ........................................................................................................................................... 9
13.2 Rapid-Fire Definitions ................................................................................................................................................. 10
13.3 Practical Tips to Mention in Interviews ..................................................................................................................... 10
1. What Is Data Visualization?
Data visualization is the practice of converting raw data into visuals — charts, graphs, and maps — so that patterns,
trends, and outliers become easy to spot at a glance.
• Numbers in a table are hard to scan; a line chart of monthly sales instantly shows the trend.
• Goal: make data clear, simple, and easy to understand — for yourself and for stakeholders.
Interview angle: Be ready to explain WHY visualization matters (faster pattern recognition, easier anomaly/outlier
detection, better communication to non-technical stakeholders) — not just HOW to code a plot.
2. Introduction to Matplotlib
Matplotlib is a Python library purpose-built for creating visualizations. It's mature, widely adopted, and used across
data science, research, engineering, statistics, and business analytics.
Why Matplotlib is powerful
• Supports many plot types: line, bar, scatter, histogram, pie, box, 3D.
• Fully customizable — colors, line styles, markers, labels, titles, legends.
• Low-level control, which makes it the foundation many higher-level libraries (like Seaborn) are built on top of.
Two Ways to Plot in Matplotlib
API Import / Entry Point Description Best For
Simpler, state-based, function- Quick, one-off plots;
Pyplot API import [Link] as plt
driven ([Link](), [Link]()) exploratory analysis
You create Figure & Axes objects
Complex, multi-plot layouts;
Object-Oriented (OO) API fig, ax = [Link]() explicitly and call methods on
production code; apps
them
3. Anatomy of a Matplotlib Figure
A Figure is the entire canvas/window. It contains all visual components:
Component What It Represents
Figure The whole window/page/canvas that holds everything
Axes The actual plot area (X-axis and Y-axis) drawn inside the figure
Axis Labels Text describing what the X and Y axes represent (e.g., "Hours Studied", "Marks")
Major Ticks The main numbered marks on an axis (e.g., 0, 1, 2, 3)
Minor Ticks The in-between marks (e.g., 0.25, 0.5, 0.75)
Legend Key that maps colors/markers to what they represent
Gridlines Dotted background lines that make the plot easier to read precisely
Title Label for the whole figure/plot
Interview Q: "What is the difference between a Figure and an Axes in Matplotlib?" — Figure = the whole
canvas/container; Axes = an individual plot (with its own X/Y axis) living inside that canvas. One Figure can hold
multiple Axes (subplots).
4. Installation & Import
pip install matplotlib
import [Link] as plt
import pandas as pd
Confirm success by seeing "Requirement already satisfied" or a clean install log.
Minimal Example
x = [1, 2, 3]
y = [4, 5, 6]
[Link](x, y)
[Link]() # adds dotted gridlines for easier reading
[Link]()
[Link](x, y) plots point pairs: (1,4), (2,5), (3,6) and connects them with a line.
5. Univariate vs Bivariate vs Multivariate Analysis
Which plot to use depends on (a) how many columns/variables you're analyzing together, and (b) whether each column
is numerical or categorical.
Analysis Type # of Variables Meaning
Univariate 1 Study a single column in isolation (numerical OR categorical)
Bivariate 2 Study the relationship between two columns
Multivariate 3+ Study how three or more columns interact together
6. Univariate Analysis
6.1 Single Numerical Column
Line Plot
[Link](df['salary'], color='red', marker='o', linestyle='--', linewidth=2)
[Link]()
[Link]()
• color — line color
• marker — symbol at each data point (e.g. 'o' circle, '*' star)
• linestyle — '-' solid, '--' dashed, ':' dotted
• linewidth — thickness of the line
Histogram
[Link](df['salary'], bins=5, color='green')
[Link]()
A histogram shows the frequency distribution of a numerical column — how many records fall into each value range
("bin"). More bins = finer granularity.
Box Plot (Box-and-Whisker)
[Link](df['salary'])
[Link]()
A box plot summarizes a distribution using five key statistics:
Term Meaning
Minimum Smallest non-outlier value (end of lower whisker)
Q1 (Lower Quartile) 25th percentile — 25% of data falls below this
Median (Q2) 50th percentile — the middle value
Q3 (Upper Quartile) 75th percentile — 75% of data falls below this
Maximum Largest non-outlier value (end of upper whisker)
IQR (Interquartile Range) Q3 − Q1; the "box" itself, containing the middle 50% of data
Outliers Points beyond the whiskers (unusually high/low) — plotted individually
Interview Q: "How do you detect outliers visually?" — A box plot: any point plotted outside the whiskers (beyond
~1.5×IQR from Q1/Q3) is an outlier. This is a classic data-cleaning / EDA step before model training.
6.2 Single Categorical Column
Pie Chart
count = df['department'].value_counts()
[Link](count, labels=[Link], autopct='%1.1f%%',
explode=[0, 0.1, 0.2], shadow=True)
[Link]('equal') # keeps the pie circular
[Link]()
• labels — names each slice
• autopct='%1.1f%%' — displays percentage per slice (1 decimal place)
• explode — pulls a slice away from the center by a given distance
• shadow=True — adds a drop-shadow for a pseudo-3D look
• axis('equal') — forces the pie into a perfect circle
Bar / Count Plot
[Link]([Link], count, color=['green', 'black', 'red'])
[Link]()
Shows the count of records per category as bars — easier to compare exact magnitudes than a pie chart.
7. Bivariate Analysis
7.1 Numerical vs Numerical
Scatter Plot
[Link](df['age'], df['salary'], color='orange')
[Link]()
Reveals correlation between two numerical variables. Points trending up-right = positive correlation (e.g., salary rises
with age).
Line Plot (sorted)
sort_age = df.sort_values('age')
[Link](sort_age['age'], sort_age['salary'])
[Link]()
Gotcha: A line plot needs the X variable sorted first, otherwise the line zig-zags back and forth meaninglessly — a
common beginner mistake worth mentioning in interviews.
Bar Plot
[Link](sort_age['age'], sort_age['salary'], align='center', color='green')
[Link]()
7.2 Numerical vs Categorical
Box Plot (grouped by category)
hr = df[df['department']=='HR']['salary']
it = df[df['department']=='IT']['salary']
fin = df[df['department']=='Finance']['salary']
[Link]([hr, it, fin], labels=['HR', 'IT', 'Finance'])
[Link]()
[Link]()
Lets you compare salary distribution (median, spread, outliers) across each department side by side.
Pie Chart (aggregated)
grouped = [Link]('department')['salary'].sum()
[Link](grouped, labels=[Link], autopct='%1.1f%%')
[Link]()
groupby + sum() aggregates the numerical column per category before plotting — shows each department's share of
total salary.
Bar Plot (mean per category)
hr_mean = [Link]() / len(hr)
it_mean = [Link]() / len(it)
fin_mean = [Link]() / len(fin)
[Link](['HR', 'IT', 'Finance'], [hr_mean, it_mean, fin_mean],
color=['green', 'black', 'red'])
[Link]()
[Link]()
(In practice: [Link]('department')['salary'].mean() does this in one line.)
8. Multivariate Analysis
8.1 Three Numerical Columns → Bubble Plot
[Link](df['age'], df['salary'], s=df['experience']*20, color='blue')
[Link]('Age vs Salary vs Experience')
[Link]('Age'); [Link]('Salary')
[Link]()
A bubble plot is a scatter plot where a third numerical column controls marker size (s=...). Bigger bubble = higher
value of the third variable (e.g., more experience).
8.2 Two Numerical + One Categorical → Color-Coded Scatter
colors = {'HR': 'yellow', 'IT': 'blue', 'Finance': 'orange'}
for dept, color in [Link]():
subset = df[df['department'] == dept]
[Link](subset['age'], subset['salary'], color=color, label=dept)
[Link]('Age'); [Link]('Salary')
[Link]()
[Link]()
Gotcha: If you map colors manually via df['dept'].map({...}) and pass that directly to color=, [Link]() will NOT
auto-generate correctly. You must loop through categories and call scatter() once per category with an explicit label=
to get a working legend.
8.3 Multiple Numerical Columns vs One Shared X → Multi-Line Plot
[Link](df2['year'], df2['sales'], label='Sales')
[Link](df2['year'], df2['profit'], label='Profit')
[Link](df2['year'], df2['expenses'], label='Expenses')
[Link]('Financial Analysis')
[Link]('Year'); [Link]('Amount')
[Link]()
[Link]()
Useful for dashboards / financial trend analysis — multiple metrics plotted against a common axis (e.g., year) in a
single chart.
9. Object-Oriented API — Subplots
The OO API lets you build multiple plots/axes inside one figure — essential for dashboards and side-by-side
comparisons.
fig, axis = [Link](1, 3, figsize=(15, 5))
# Plot 1: Line plot
axis[0].plot(sort_age['age'], sort_age['salary'], color='red',
marker='*', linewidth=2, markersize=2)
axis[0].grid()
axis[0].set_title('Line Plot')
axis[0].set_xlabel('Age'); axis[0].set_ylabel('Salary')
# Plot 2: Histogram
axis[1].hist(df['salary'], color='skyblue')
axis[1].set_title('Histogram')
axis[1].set_xlabel('Salary'); axis[1].set_ylabel('Frequency')
# Plot 3: Box plot
axis[2].boxplot(df['salary'])
axis[2].set_title('Box Plot')
axis[2].set_xlabel('Salary')
[Link]()
• [Link](rows, cols) returns a Figure and an array of Axes objects.
• figsize=(width, height) controls the overall canvas dimensions (inches).
• Each axis[i] behaves like its own mini pyplot — set_title(), set_xlabel(), set_ylabel() instead of [Link](),
[Link]().
Interview Q: "Why use the OO API instead of Pyplot?" — Pyplot is stateful/global (implicitly tracks "current"
figure/axes), which becomes error-prone with multiple subplots. The OO API is explicit and safer for complex,
multi-panel, or production-grade visualizations.
10. Saving Figures
[Link]('multiple_plots.png') # call BEFORE [Link]()
[Link]()
Supported formats: .png, .jpg, .pdf, etc. In Jupyter/VS Code you can pass a full file path to control the save location; in
Colab it saves to the mounted Drive/session storage.
11. 3D Plots
Matplotlib 3D (best in VS Code / Jupyter — limited interactivity in Colab)
ax = [Link](projection='3d')
[Link](df['age'], df['salary'], df['experience'])
ax.set_xlabel('Age'); ax.set_ylabel('Salary'); ax.set_zlabel('Experience')
[Link]()
Plotly (fully interactive — works well in Colab)
import [Link] as px
fig = px.scatter_3d(df, x='age', y='salary', z='experience',
title='3D Scatter Plot')
[Link]()
Interview angle: Know that Matplotlib's 3D module (mpl_toolkits.mplot3d) is static/less interactive, while Plotly
renders interactive, rotatable 3D charts in the browser — a common reason teams pick Plotly for dashboards.
12. Quick Reference — "Which Plot Do I Use?"
Data Situation Recommended Plot(s)
1 numerical column Line plot, Histogram, Box plot
1 categorical column Pie chart, Bar/Count plot
Data Situation Recommended Plot(s)
2 numerical columns Scatter plot, Line plot, Bar plot
1 numerical + 1 categorical Grouped box plot, Aggregated pie chart, Bar plot of group means
3 numerical columns Bubble plot (scatter + size encoding)
2 numerical + 1 categorical Color-coded scatter plot (one color per category, with legend)
Many numerical columns vs. shared X (e.g., time) Multi-line plot (one line per metric)
3D relationship between 3 numerical columns 3D scatter plot (Matplotlib or Plotly)
13. Interview Prep — Key Concepts & Sample Q&A
Curated for AI Engineer / Data Science interviews — these are the concepts interviewers most often probe beyond "do
you know the syntax."
13.1 Core Conceptual Questions
Q: What's the difference between Matplotlib, Seaborn, and Plotly?
A: Matplotlib is the low-level foundation library — maximum control, more verbose code. Seaborn is built on top
of Matplotlib and offers higher-level, statistically-aware plots with better default styling and less code. Plotly
generates interactive, web-based, rotatable/zoomable charts, useful for dashboards and 3D visualizations.
Q: When would you choose a box plot over a histogram?
A: Use a histogram to see the full shape/frequency distribution of one variable. Use a box plot when you want a
compact summary (median, quartiles, outliers) or need to compare distributions across several categories side by
side.
Q: How do you decide which chart type to use for a given dataset?
A: First identify how many variables you're plotting and whether each is numerical or categorical
(univariate/bivariate/multivariate), then match to the standard chart types (see the Quick Reference table). The
choice should make the specific insight — trend, distribution, relationship, or composition — as obvious as
possible.
Q: What is a positive vs. negative correlation, and how do you spot it on a scatter plot?
A: Positive correlation: as one variable increases, so does the other (points trend up and to the right). Negative
correlation: as one increases, the other decreases (points trend down and to the right). No visible pattern suggests
little/no linear correlation.
Q: Why does sorting matter before drawing a line plot?
A: A line plot draws straight segments between consecutive points in the order they appear in the data. If the X
variable isn't sorted, the line zig-zags meaninglessly instead of showing a clean trend — always sort by the X
variable first.
Q: What is the difference between the Pyplot API and the Object-Oriented API?
A: Pyplot ([Link](), [Link]()...) is a simpler, implicit, state-based interface — convenient for quick single plots.
The OO API (fig, ax = [Link]()) gives explicit references to Figure and Axes objects, which is essential for
multi-subplot layouts and is generally recommended for production code.
Q: How would you visually identify outliers in a numerical feature before model training?
A: A box plot: any data point plotted beyond the whiskers (outside roughly 1.5×IQR from Q1/Q3) is flagged as an
outlier. This is a standard step in EDA / data cleaning before feeding features into an ML model.
Q: What does the `s` parameter do in [Link](), and where is it used?
A: It sets marker size — either a constant or an array mapped per point. Varying it by a third numerical column
turns a normal scatter plot into a bubble plot, letting you encode a third dimension of information in 2D.
Q: Why might [Link]() fail to show correct labels in a manually color-mapped scatter plot?
A: If colors are assigned via a dictionary/map (e.g., df['col'].map({...})) and passed directly to color=, Matplotlib
has no record of which color belongs to which category, so it can't build a legend. The fix is to loop over each
category and call scatter() separately with an explicit label= per call.
Q: How do you save a Matplotlib figure to a file, and what formats are supported?
A: [Link]('[Link]') called BEFORE [Link]() (which clears the figure from memory). Common formats:
PNG, JPG, PDF, SVG — controlled by the file extension.
13.2 Rapid-Fire Definitions
Term One-line Definition
Figure The entire canvas/window containing one or more plots
Axes An individual plot area (with X & Y axis) inside a Figure
IQR Interquartile Range = Q3 − Q1; spread of the middle 50% of data
Outlier A data point unusually far from the rest of the distribution
Univariate analysis Analyzing a single variable/column in isolation
Bivariate analysis Analyzing the relationship between two variables
Multivariate analysis Analyzing relationships among three or more variables
Bubble plot Scatter plot where marker size encodes a third numerical variable
Subplot One of multiple plots arranged together inside a single Figure
13.3 Practical Tips to Mention in Interviews
• Always start EDA (exploratory data analysis) by checking data types (numerical vs. categorical) — this drives
which visualization is even valid.
• Mention that visualization is a diagnostic step, not just presentation — e.g., spotting outliers or skew before
choosing a model or a preprocessing strategy (like scaling or log-transform).
• Know that Matplotlib underlies Pandas' own .plot() convenience methods (df['col'].plot(kind='hist')), and underlies
Seaborn — showing you understand the ecosystem, not just one library in isolation.
• Be able to explain a chart you already built out loud — e.g., "the median HR salary sits around 25–30K, IT is a bit
higher, and Finance has the highest median with one visible outlier" — interviewers often ask you to read a plot,
not just produce one.
End of notes — good luck with your interview prep!