4.1 Core Visualization with Matplotlib
4.1 Core Visualization with Matplotlib
Matplotlib is one of the most widely used Python libraries for creating static, publication-quality data visualizations.
It is especially important in Data Science because visualizations help us understand patterns, trends, distributions, relationships, and unusual observations that may not be obvious from raw data.
- What Matplotlib is and why it is used
- Installing and importing Matplotlib
- Understanding Figure, Axes, Axis, and plot elements
- Creating line charts
- Creating bar charts
- Creating histograms
- Creating scatter plots
- Adding titles, labels, legends, and grids
- Customizing markers and line styles
- Controlling axes and ticks
- Saving visualizations to files
- Choosing the right chart for a dataset
- Common mistakes and best practices
1. What Is Matplotlib?
Matplotlib is a Python library used to create graphs, charts, plots, and other data visualizations.
It can be used with Python lists, NumPy arrays, pandas Series, and pandas DataFrames.
Matplotlib is particularly useful for:
- Exploratory Data Analysis (EDA)
- Scientific computing
- Statistical analysis
- Academic research
- Business reporting
- Data Science projects
- Machine Learning analysis
2. Installing Matplotlib
If Matplotlib is not already installed, it can be installed using
pip.
pip install matplotlib
With a Conda environment:
conda install matplotlib
In a Jupyter Notebook, you can install it using:
%pip install matplotlib
If you are using Anaconda, Matplotlib is commonly included in the standard scientific Python environment.
3. Importing Matplotlib
The most common import convention is:
import matplotlib.pyplot as plt
Here:
matplotlibis the main library.pyplotprovides a convenient plotting interface.pltis the conventional alias.
Almost every Matplotlib tutorial and Data Science project uses this import.
4. Your First Matplotlib Plot
The simplest visualization can be created using
plt.plot().
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]
plt.plot(x, y)
plt.show()
The plot() function uses the values in
x as the horizontal coordinates and
y as the vertical coordinates.
plt.plot(x, y)
plt.show()
5. Understanding Plot Anatomy
A Matplotlib visualization consists of several important components.
| Component | Meaning |
|---|---|
| Figure | The overall drawing area or canvas. |
| Axes | The actual plotting area containing the data. |
| X-axis | Horizontal axis. |
| Y-axis | Vertical axis. |
| Title | Describes what the visualization represents. |
| Axis labels | Describe the variables represented by the axes. |
| Legend | Identifies different data series. |
| Grid | Provides visual reference lines. |
| Ticks | Reference values displayed along an axis. |
| Markers | Symbols used to identify individual observations. |
6. Adding a Chart Title
Use plt.title() to add a title.
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [120, 150, 135, 180]
plt.plot(months, sales)
plt.title("Monthly Sales")
plt.show()
A meaningful title should communicate what the chart shows.
Monthly Sales Performance
Weak title:Graph 1
7. Adding Axis Labels
Use plt.xlabel() and plt.ylabel().
plt.xlabel("Month")
plt.ylabel("Sales")
Complete example:
plt.plot(months, sales)
plt.title("Monthly Sales Performance")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
8. Adding a Grid
A grid can make values easier to read.
plt.grid()
Example:
plt.plot(months, sales)
plt.title("Monthly Sales Performance")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid()
plt.show()
Use grids when they improve readability. Avoid excessive visual decoration that competes with the data.
9. Controlling Figure Size
Use figsize with plt.figure().
plt.figure(figsize=(10, 5))
plt.plot(months, sales)
plt.show()
The values represent:
- Width
- Height
The default unit is inches.
10. Line Charts
A line chart connects data points with lines. It is particularly useful for showing trends and ordered observations.
Common applications include:
- Monthly sales
- Temperature over time
- Stock prices
- Website traffic
- Student performance over examinations
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May"
]
sales = [
120,
150,
135,
180,
210
]
plt.plot(months, sales)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
11. Customizing Line Styles
The linestyle parameter controls the appearance of
the line.
plt.plot(
months,
sales,
linestyle="--"
)
Common styles include:
| Style | Meaning |
|---|---|
- |
Solid line |
-- |
Dashed line |
: |
Dotted line |
-. |
Dash-dot line |
12. Adding Markers
Markers identify individual observations.
plt.plot(
months,
sales,
marker="o"
)
A complete example:
plt.plot(
months,
sales,
marker="o",
linestyle="-"
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
Common marker symbols include:
o— circles— square^— triangle*— starx— x marker
13. Plotting Multiple Lines
Multiple datasets can be plotted on the same axes.
months = [
"Jan",
"Feb",
"Mar",
"Apr"
]
online = [100, 120, 150, 170]
store = [80, 95, 110, 125]
plt.plot(
months,
online,
marker="o",
label="Online"
)
plt.plot(
months,
store,
marker="s",
label="Store"
)
plt.title("Sales Comparison")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.show()
14. Adding a Legend
A legend identifies different data series.
plt.legend()
Each series should have a label.
plt.plot(
months,
online,
label="Online"
)
plt.plot(
months,
store,
label="Store"
)
plt.legend()
Calling plt.legend() without assigning labels to
plotted series may result in an empty or incomplete legend.
15. Bar Charts
A bar chart compares values across discrete categories.
Examples:
- Sales by product
- Students by department
- Population by country
- Revenue by region
products = [
"Laptop",
"Tablet",
"Phone",
"Monitor"
]
sales = [
120,
85,
160,
70
]
plt.bar(
products,
sales
)
plt.title("Product Sales")
plt.xlabel("Product")
plt.ylabel("Units Sold")
plt.show()
16. Horizontal Bar Charts
Use plt.barh() to create horizontal bars.
plt.barh(
products,
sales
)
plt.title("Product Sales")
plt.xlabel("Units Sold")
plt.ylabel("Product")
plt.show()
Horizontal bars are often easier to read when category names are long.
17. Customizing Bar Charts
Bars can be customized using parameters such as
width, edgecolor, and
alpha.
plt.bar(
products,
sales,
width=0.6,
edgecolor="black",
alpha=0.8
)
plt.title("Product Sales")
plt.xlabel("Product")
plt.ylabel("Units Sold")
plt.show()
Do not over-customize charts. Formatting should improve interpretation rather than distract from the data.
18. Histograms
A histogram shows the distribution of numerical data by dividing values into intervals called bins.
Histograms are useful for understanding:
- Distribution
- Central tendency
- Spread
- Skewness
- Potential outliers
scores = [
55, 62, 68, 70, 72,
75, 78, 80, 82, 85,
87, 90, 92, 95, 98
]
plt.hist(scores)
plt.title("Distribution of Scores")
plt.xlabel("Score")
plt.ylabel("Frequency")
plt.show()
19. Controlling Histogram Bins
The bins parameter controls how many intervals are
used.
plt.hist(
scores,
bins=5
)
More bins provide finer detail, while fewer bins provide a broader view of the distribution.
There is no universally correct number of bins. Choose a bin configuration that reveals the distribution without creating unnecessary noise.
20. Scatter Plots
A scatter plot displays the relationship between two numerical variables.
It is useful for investigating possible:
- Correlation
- Trends
- Clusters
- Outliers
- Relationships between variables
hours = [
1, 2, 3, 4, 5,
6, 7, 8
]
scores = [
45, 50, 55, 62,
68, 74, 82, 88
]
plt.scatter(
hours,
scores
)
plt.title("Study Hours vs Score")
plt.xlabel("Study Hours")
plt.ylabel("Score")
plt.show()
21. Customizing Scatter Plots
plt.scatter(
hours,
scores,
marker="o",
alpha=0.7
)
plt.title("Study Hours vs Score")
plt.xlabel("Study Hours")
plt.ylabel("Score")
plt.show()
The alpha parameter controls transparency and can be
useful when many points overlap.
22. Controlling Axis Limits
Use plt.xlim() and plt.ylim() to control
the visible range.
plt.xlim(0, 10)
plt.ylim(0, 100)
Example:
plt.scatter(
hours,
scores
)
plt.xlim(0, 10)
plt.ylim(0, 100)
plt.xlabel("Study Hours")
plt.ylabel("Score")
plt.show()
23. Controlling Ticks
Tick positions and labels can be customized using
plt.xticks() and plt.yticks().
plt.xticks(
[1, 2, 3, 4, 5]
)
plt.yticks(
[0, 20, 40, 60, 80, 100]
)
This is useful when the default tick spacing is not suitable for your visualization.
24. Comparing Multiple Datasets
Multiple datasets can be displayed in one chart when they share comparable units and the comparison is meaningful.
months = [
"Jan",
"Feb",
"Mar",
"Apr"
]
science = [72, 78, 84, 88]
mathematics = [68, 75, 81, 90]
plt.plot(
months,
science,
marker="o",
label="Science"
)
plt.plot(
months,
mathematics,
marker="s",
label="Mathematics"
)
plt.title("Subject Performance")
plt.xlabel("Month")
plt.ylabel("Average Score")
plt.legend()
plt.grid()
plt.show()
25. Understanding Figure and Axes Objects
Matplotlib can be used through its object-oriented interface. This approach becomes particularly useful for complex visualizations.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(
months,
sales
)
ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
plt.show()
fig represents the Figure, while
ax represents an Axes object where the data is
plotted.
26. Pyplot Style vs Object-Oriented Style
| Pyplot Style | Object-Oriented Style |
|---|---|
plt.plot() |
ax.plot() |
plt.title() |
ax.set_title() |
plt.xlabel() |
ax.set_xlabel() |
plt.ylabel() |
ax.set_ylabel() |
| Simple scripts and learning | Complex and reusable visualizations |
Learn both styles. The object-oriented approach is especially valuable when creating multiple plots or building reusable visualization code.
27. Creating Multiple Plots with Subplots
Multiple charts can be placed inside one Figure.
fig, axes = plt.subplots(
1,
2,
figsize=(10, 4)
)
axes[0].plot(
months,
sales
)
axes[0].set_title(
"Sales Trend"
)
axes[1].bar(
products,
[120, 85, 160, 70]
)
axes[1].set_title(
"Product Sales"
)
plt.show()
Here, two Axes objects are created in one row.
28. Improving Layout with tight_layout()
When multiple plots contain long labels or titles, elements may overlap.
plt.tight_layout()
With the object-oriented approach:
fig.tight_layout()
Consider using tight_layout() when creating
multiple subplots or charts with extensive labels.
29. Saving a Visualization
Use plt.savefig() to save a chart.
plt.plot(
months,
sales
)
plt.title("Monthly Sales")
plt.savefig(
"monthly_sales.png"
)
plt.show()
Matplotlib can save visualizations in commonly used formats such as PNG, JPG, SVG, and PDF, depending on the requirements.
30. Why Save Before show()?
A safe and common workflow is:
plt.savefig("chart.png")
plt.show()
Saving before displaying helps avoid situations where the displayed figure has already been cleared or altered by the plotting workflow.
31. Complete Line Chart Example
import matplotlib.pyplot as plt
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun"
]
revenue = [
120,
135,
150,
142,
170,
190
]
plt.figure(figsize=(10, 5))
plt.plot(
months,
revenue,
marker="o",
linestyle="-",
label="Revenue"
)
plt.title(
"Monthly Revenue Trend"
)
plt.xlabel(
"Month"
)
plt.ylabel(
"Revenue"
)
plt.grid()
plt.legend()
plt.tight_layout()
plt.show()
32. Complete Bar Chart Example
import matplotlib.pyplot as plt
departments = [
"Science",
"Commerce",
"Humanities",
"Technology"
]
students = [
180,
150,
120,
210
]
plt.figure(figsize=(9, 5))
plt.bar(
departments,
students
)
plt.title(
"Students by Department"
)
plt.xlabel(
"Department"
)
plt.ylabel(
"Number of Students"
)
plt.grid(
axis="y"
)
plt.tight_layout()
plt.show()
33. Complete Histogram Example
import matplotlib.pyplot as plt
scores = [
45, 52, 56, 61, 64,
67, 69, 71, 73, 75,
78, 80, 82, 85, 87,
89, 91, 94, 96, 98
]
plt.figure(figsize=(9, 5))
plt.hist(
scores,
bins=5
)
plt.title(
"Distribution of Examination Scores"
)
plt.xlabel(
"Score"
)
plt.ylabel(
"Number of Students"
)
plt.tight_layout()
plt.show()
34. Complete Scatter Plot Example
import matplotlib.pyplot as plt
study_hours = [
1, 2, 2.5, 3,
4, 4.5, 5,
6, 7, 8
]
scores = [
42, 48, 52, 58,
64, 68, 72,
78, 85, 92
]
plt.figure(figsize=(9, 5))
plt.scatter(
study_hours,
scores,
alpha=0.7
)
plt.title(
"Study Hours vs Examination Score"
)
plt.xlabel(
"Study Hours"
)
plt.ylabel(
"Examination Score"
)
plt.grid()
plt.tight_layout()
plt.show()
35. Matplotlib with pandas
Matplotlib works naturally with pandas DataFrames.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"Month": [
"Jan",
"Feb",
"Mar",
"Apr"
],
"Sales": [
120,
150,
135,
180
]
})
plt.plot(
df["Month"],
df["Sales"]
)
plt.title(
"Monthly Sales"
)
plt.xlabel(
"Month"
)
plt.ylabel(
"Sales"
)
plt.show()
This is a common workflow in Data Science:
36. Choosing the Right Chart
| Question | Recommended Chart |
|---|---|
| How does a value change over time? | Line chart |
| How do categories compare? | Bar chart |
| How is numerical data distributed? | Histogram |
| Is there a relationship between two numerical variables? | Scatter plot |
| What are individual observations over an ordered scale? | Line or scatter plot |
- Trend → Line
- Compare → Bar
- Distribution → Histogram
- Relationship → Scatter
37. Line Chart vs Bar Chart
Choosing between line and bar charts depends on the meaning of the x-axis.
| Line Chart | Bar Chart |
|---|---|
| Emphasizes continuity or progression. | Emphasizes category comparison. |
| Excellent for time series. | Excellent for independent categories. |
| Shows trends clearly. | Shows magnitude clearly. |
38. Principles of Effective Visualization
- Give the chart a meaningful title.
- Label the axes.
- Use appropriate scales.
- Choose a chart based on the analytical question.
- Avoid unnecessary decoration.
- Keep legends clear and meaningful.
- Use readable category labels.
- Do not hide important observations.
- Use consistent units.
- Make the visualization understandable without requiring the reader to inspect the code.
39. Common Matplotlib Mistakes
-
Forgetting
plt.show(): The plot may not display as expected in some environments. - Missing axis labels: Readers may not understand what the values represent.
- Using the wrong chart: A histogram and bar chart answer different questions.
- Too many lines: A chart can become difficult to interpret.
- Overusing formatting: Visual decoration should not overpower the data.
- Ignoring scale: Poor axis choices can make patterns misleading.
- Missing legends: Multiple series become difficult to identify.
- Unreadable labels: Long category names may require a horizontal bar chart or adjusted layout.
40. Common Errors and Solutions
| Error / Problem | Likely Cause | Solution |
|---|---|---|
NameError: plt is not defined |
Matplotlib was not imported. | Use import matplotlib.pyplot as plt. |
| Incorrect number of points | X and Y lengths differ. | Ensure corresponding values have matching lengths. |
| Overlapping labels | Figure is too small. | Increase figure size or use tight_layout(). |
| Legend is empty | Plots do not have labels. | Add label=... before calling legend(). |
41. Matplotlib Interview Questions
Q1. What is Matplotlib?
View Answer
Matplotlib is a Python visualization library used to create charts and graphs for data analysis, scientific computing, and presentation.
Q2. What is pyplot?
View Answer
pyplot is a Matplotlib module that provides a
convenient interface for creating and controlling plots.
Q3. Why is matplotlib.pyplot commonly imported
as plt?
View Answer
plt is the conventional short alias that
makes plotting commands concise and readable.
Q4. What is the difference between a bar chart and a histogram?
View Answer
A bar chart compares discrete categories, while a histogram displays the distribution of numerical data grouped into bins.
Q5. When should you use a scatter plot?
View Answer
A scatter plot is used to examine the relationship, association, clustering, or potential correlation between two numerical variables.
Q6. What is the purpose of plt.show()?
View Answer
It displays the current Matplotlib figure.
Q7. What does plt.legend() do?
View Answer
It displays a legend identifying plotted data series that have been assigned labels.
Q8. What is the purpose of figsize?
View Answer
figsize controls the width and height of a
Matplotlib Figure.
Q9. What is the difference between Figure and Axes?
View Answer
A Figure is the overall canvas, while an Axes object is the plotting area on which data is drawn.
Q10. What does plt.savefig() do?
View Answer
It saves the current visualization to a file.
42. Examination Questions — MCQs
Q1. Which module is commonly used for plotting with Matplotlib?
matplotlib.datamatplotlib.pyplotmatplotlib.plottingmatplotlib.graph
Answer: B — matplotlib.pyplot
Q2. Which function creates a line plot?
plt.line()plt.graph()plt.plot()plt.drawline()
Answer: C — plt.plot()
Q3. Which function creates a bar chart?
plt.bar()plt.column()plt.compare()plt.category()
Answer: A — plt.bar()
Q4. Which chart is best for showing a numerical distribution?
- Histogram
- Line chart
- Bar chart
- Scatter plot
Answer: A — Histogram
Q5. Which function creates a scatter plot?
plt.points()plt.scatter()plt.relationship()plt.dot()
Answer: B — plt.scatter()
Q6. Which parameter controls histogram intervals?
groupsintervalsbinsranges
Answer: C — bins
Q7. Which function adds a title?
plt.heading()plt.caption()plt.title()plt.name()
Answer: C — plt.title()
Q8. Which function saves a Matplotlib figure?
plt.store()plt.save()plt.savefig()plt.export()
Answer: C — plt.savefig()
43. Practical Examination Questions
Question 1 — Line Chart
Create a line chart showing monthly website visitors.
import matplotlib.pyplot as plt
months = [
"Jan",
"Feb",
"Mar",
"Apr"
]
visitors = [
1200,
1500,
1800,
2100
]
plt.plot(
months,
visitors,
marker="o"
)
plt.title(
"Monthly Website Visitors"
)
plt.xlabel("Month")
plt.ylabel("Visitors")
plt.grid()
plt.show()
Question 2 — Bar Chart
Create a bar chart showing the number of students in four departments.
departments = [
"Science",
"Commerce",
"Humanities",
"Technology"
]
students = [
180,
150,
120,
210
]
plt.bar(
departments,
students
)
plt.title(
"Students by Department"
)
plt.xlabel("Department")
plt.ylabel("Students")
plt.show()
Question 3 — Histogram
Create a histogram showing examination-score distribution.
scores = [
45, 52, 56, 61,
64, 67, 70, 72,
75, 78, 81, 84,
87, 90, 94, 98
]
plt.hist(
scores,
bins=5
)
plt.title(
"Examination Score Distribution"
)
plt.xlabel("Score")
plt.ylabel("Frequency")
plt.show()
Question 4 — Scatter Plot
Create a scatter plot showing the relationship between study hours and examination scores.
hours = [
1, 2, 3, 4,
5, 6, 7, 8
]
scores = [
42, 50, 58, 64,
70, 76, 84, 91
]
plt.scatter(
hours,
scores
)
plt.title(
"Study Hours vs Examination Score"
)
plt.xlabel("Study Hours")
plt.ylabel("Score")
plt.show()
44. Scenario-Based Questions
Scenario 1: A Data Scientist wants to show how revenue changed every month during a year.
Best choice: Line chart.
Scenario 2: A company wants to compare sales for five different products.
Best choice: Bar chart.
Scenario 3: A researcher wants to understand the distribution of student examination scores.
Best choice: Histogram.
Scenario 4: A researcher wants to investigate whether study time and examination scores are associated.
Best choice: Scatter plot.
Scenario 5: A report contains very long category names that do not fit comfortably along the horizontal axis.
Possible solution:
Use a horizontal bar chart with plt.barh().
45. Professional Matplotlib Tips
- Always give important charts a meaningful title.
- Label both axes and include units when appropriate.
- Choose the visualization based on the analytical question.
- Keep the number of visual elements under control.
- Use legends when multiple datasets are displayed.
-
Use
tight_layout()when labels or titles overlap. -
Use
figsizeto create readable charts. -
Save important visualizations using
savefig(). - For complex visualizations, prefer the object-oriented Matplotlib interface.
- Do not manipulate axes merely to make a result look more impressive. The visualization should represent the data honestly.
46. Matplotlib Quick Revision Cheatsheet
| Command | Purpose |
|---|---|
import matplotlib.pyplot as plt |
Import pyplot. |
plt.plot(x, y) |
Create a line chart. |
plt.bar(x, y) |
Create a vertical bar chart. |
plt.barh(x, y) |
Create a horizontal bar chart. |
plt.hist(data) |
Create a histogram. |
plt.scatter(x, y) |
Create a scatter plot. |
plt.title() |
Add a title. |
plt.xlabel() |
Label the X-axis. |
plt.ylabel() |
Label the Y-axis. |
plt.legend() |
Display a legend. |
plt.grid() |
Display grid lines. |
plt.xlim() |
Set X-axis limits. |
plt.ylim() |
Set Y-axis limits. |
plt.xticks() |
Control X-axis ticks. |
plt.yticks() |
Control Y-axis ticks. |
plt.figure(figsize=(w, h)) |
Set figure dimensions. |
plt.tight_layout() |
Improve spacing. |
plt.savefig() |
Save the figure. |
plt.show() |
Display the figure. |
fig, ax = plt.subplots() |
Create Figure and Axes objects. |
47. Key Takeaways
- Matplotlib is a fundamental Python library for data visualization.
-
matplotlib.pyplotis commonly imported asplt. -
plt.plot()creates line charts. -
plt.bar()creates bar charts. -
plt.hist()creates histograms. -
plt.scatter()creates scatter plots. - Titles, labels, legends, grids, and appropriate scales improve interpretation.
- The Figure is the overall canvas, while Axes represent individual plotting areas.
- Matplotlib integrates naturally with pandas and NumPy.
- Visualization should communicate an analytical message, rather than simply decorate the dataset.
Trend → Line | Comparison → Bar | Distribution → Histogram | Relationship → Scatter