Matplotlib for Data Science
A Practical Python Tutorial with Examples and Output
Introduction to Matplotlib
Matplotlib is a Python library used to create visualizations such as line charts, bar charts,
scatter plots, histograms, pie charts and many other types of graphs.
It is widely used in Data Science, Machine Learning, Scientific Computing, Statistics
and data analysis. The matplotlib.pyplot interface provides convenient plotting
functions, while Matplotlib also supports an object-oriented approach using Figure and Axes objects.
Student Tip: Learn Matplotlib after NumPy because NumPy arrays are commonly used as
the numerical input for plotting.
1. Installing Matplotlib
Matplotlib can be installed using pip.
pip install matplotlib
After installation, import the pyplot module.
import matplotlib.pyplot as plt
Output
Matplotlib imported successfully.
2. Creating a Simple Line Plot
The plot() function is one of the most commonly used Matplotlib functions.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.plot(x, y)
plt.show()
Output
A line graph is displayed with the values of x on the horizontal axis
and y on the vertical axis.
3. Adding a Title
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.plot(x, y)
plt.title("Student Performance")
plt.show()
Output
Student Performance
The graph appears with Student Performance as its title.
4. Adding X-Axis and Y-Axis Labels
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.plot(x, y)
plt.title("Student Performance")
plt.xlabel("Study Hours")
plt.ylabel("Marks")
plt.show()
Output
The graph contains:
- Title: Student Performance
- X-axis: Study Hours
- Y-axis: Marks
5. Adding Markers
Markers can be used to show individual data points.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [20, 35, 30, 50, 45]
plt.plot(x, y, marker='o')
plt.title("Marks")
plt.xlabel("Student")
plt.ylabel("Marks")
plt.show()
Output
A line graph is displayed with circular markers at every data point.
6. Changing Line Style
Matplotlib allows different line styles such as solid, dashed and dotted lines.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 25, 20, 40, 35]
plt.plot(x, y, linestyle='--')
plt.title("Dashed Line")
plt.show()
Output
A dashed line graph is displayed.
7. Multiple Lines in One Graph
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5]
sales = [100, 120, 150, 170, 200]
profit = [20, 30, 35, 45, 55]
plt.plot(months, sales)
plt.plot(months, profit)
plt.title("Sales and Profit")
plt.xlabel("Month")
plt.ylabel("Amount")
plt.show()
Output
Two lines are displayed on the same graph representing Sales and Profit.
8. Adding a Legend
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5]
sales = [100, 120, 150, 170, 200]
profit = [20, 30, 35, 45, 55]
plt.plot(months, sales, label="Sales")
plt.plot(months, profit, label="Profit")
plt.title("Sales and Profit")
plt.xlabel("Month")
plt.ylabel("Amount")
plt.legend()
plt.show()
Output
The graph displays a legend identifying the two lines as Sales and Profit.
9. Adding Grid Lines
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y, marker='o')
plt.grid()
plt.title("Line Graph with Grid")
plt.show()
Output
Grid lines are displayed behind the graph to make the values easier to read.
10. Creating a Bar Chart
The bar() function is useful for comparing categorical values.
import matplotlib.pyplot as plt
subjects = ["C", "Python", "Java", "DBMS"]
marks = [75, 85, 80, 70]
plt.bar(subjects, marks)
plt.title("Subject-wise Marks")
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.show()
Output
A bar chart displays the marks obtained in C, Python, Java and DBMS.
11. Horizontal Bar Chart
import matplotlib.pyplot as plt
subjects = ["C", "Python", "Java", "DBMS"]
marks = [75, 85, 80, 70]
plt.barh(subjects, marks)
plt.title("Subject-wise Marks")
plt.xlabel("Marks")
plt.ylabel("Subjects")
plt.show()
Output
A horizontal bar chart is displayed.
12. Creating a Scatter Plot
A scatter plot displays individual observations as points and is useful for studying relationships
between two numerical variables.
import matplotlib.pyplot as plt
study = [1, 2, 3, 4, 5, 6]
marks = [40, 45, 55, 65, 75, 85]
plt.scatter(study, marks)
plt.title("Study Hours vs Marks")
plt.xlabel("Study Hours")
plt.ylabel("Marks")
plt.show()
Output
A scatter plot is displayed showing the relationship between study hours and marks.
13. Creating a Histogram
A histogram shows the distribution of numerical data by grouping values into bins.
import matplotlib.pyplot as plt
marks = [45, 50, 52, 55, 60, 62, 65, 68,
70, 72, 75, 78, 80, 85, 90]
plt.hist(marks, bins=5)
plt.title("Distribution of Marks")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.show()
Output
A histogram displays how frequently marks occur within different ranges.
14. Creating a Pie Chart
import matplotlib.pyplot as plt
subjects = ["C", "Python", "Java", "DBMS"]
marks = [75, 85, 80, 70]
plt.pie(marks, labels=subjects, autopct='%1.1f%%')
plt.title("Subject-wise Marks Distribution")
plt.show()
Output
A pie chart is displayed showing the percentage contribution of each subject.
15. Exploding a Pie Chart Slice
import matplotlib.pyplot as plt
subjects = ["C", "Python", "Java", "DBMS"]
marks = [75, 85, 80, 70]
explode = [0, 0.1, 0, 0]
plt.pie(
marks,
labels=subjects,
explode=explode,
autopct='%1.1f%%'
)
plt.title("Subject-wise Marks")
plt.show()
Output
The Python portion is separated slightly from the center of the pie chart.
16. Creating Subplots
Subplots allow multiple graphs to be displayed within the same figure.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.title("Line Plot")
plt.subplot(1, 2, 2)
plt.bar(x, y)
plt.title("Bar Plot")
plt.show()
Output
Two plots are displayed side by side:
17. Using Figure and Axes
For more structured and reusable visualizations, Matplotlib supports the object-oriented approach
using a Figure and one or more Axes.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 30]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("Simple Plot")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")
plt.show()
Output
A line plot is displayed with a title and axis labels.
18. Changing Figure Size
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.figure(figsize=(8, 5))
plt.plot(x, y)
plt.title("Large Figure")
plt.show()
Output
The graph is displayed using a figure size of 8 × 5 inches.
19. Saving a Graph
A Matplotlib figure can be saved to an image file using savefig().
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.plot(x, y)
plt.title("My Graph")
plt.savefig("my_graph.png")
plt.show()
Output
my_graph.png
The graph is saved as my_graph.png.
20. Practical Example — Student Performance
The following example combines several Matplotlib features to visualize student performance.
import matplotlib.pyplot as plt
students = ["A", "B", "C", "D", "E"]
marks = [65, 72, 88, 55, 92]
plt.bar(students, marks)
plt.title("Student Performance")
plt.xlabel("Students")
plt.ylabel("Marks")
plt.ylim(0, 100)
plt.grid(axis='y')
plt.show()
Output
A bar chart is displayed showing the marks of five students.
The Y-axis ranges from 0 to 100.
21. Practical Example — Sales Analysis
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [120, 150, 135, 180, 210, 240]
plt.plot(
months,
sales,
marker='o'
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid()
plt.show()
Output
A line chart displays the monthly sales trend from January to June.
22. Practical Example — Study Hours and Marks
import matplotlib.pyplot as plt
study_hours = [1, 2, 3, 4, 5, 6, 7]
marks = [35, 42, 50, 61, 70, 82, 90]
plt.scatter(study_hours, marks)
plt.title("Study Hours vs Marks")
plt.xlabel("Study Hours")
plt.ylabel("Marks")
plt.grid()
plt.show()
Output
A scatter plot shows the relationship between study hours and marks.
23. Important Matplotlib Plotting Functions
| Function |
Purpose |
plt.plot() |
Line plot |
plt.bar() |
Vertical bar chart |
plt.barh() |
Horizontal bar chart |
plt.scatter() |
Scatter plot |
plt.hist() |
Histogram |
plt.pie() |
Pie chart |
plt.subplot() |
Create subplot |
plt.show() |
Display figure |
plt.savefig() |
Save figure |
24. Important Matplotlib Commands
| Command |
Purpose |
plt.title() |
Set graph title |
plt.xlabel() |
Label X-axis |
plt.ylabel() |
Label Y-axis |
plt.legend() |
Display legend |
plt.grid() |
Display grid |
plt.xlim() |
Set X-axis limits |
plt.ylim() |
Set Y-axis limits |
plt.figure() |
Create/configure a figure |
plt.show() |
Display the graph |
25. Matplotlib with NumPy
NumPy and Matplotlib are frequently used together for numerical data analysis and visualization.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.5)
y = x ** 2
plt.plot(x, y)
plt.title("y = x²")
plt.xlabel("x")
plt.ylabel("y")
plt.grid()
plt.show()
Output
A smooth line graph representing the mathematical function y = x² is displayed.
26. Matplotlib in Data Science
Matplotlib is useful when data scientists need to understand data visually.
Graphs can reveal trends, relationships, distributions and unusual observations that may
not be obvious from raw numerical values.
- Line Plot: Useful for trends over time.
- Bar Chart: Useful for comparing categories.
- Scatter Plot: Useful for relationships between numerical variables.
- Histogram: Useful for understanding distributions.
- Pie Chart: Useful for showing proportions.
27. Figure and Axes — Basic Concept
Figure: The complete visualization window or canvas.
Axes: The area inside a figure where data is actually plotted.
Axis: The numerical or categorical scale shown along the X-axis or Y-axis.
A figure can contain one or more Axes. This is particularly useful when creating dashboards
or multiple related visualizations.
28. Complete Example
import numpy as np
import matplotlib.pyplot as plt
students = np.array([
"A", "B", "C", "D", "E"
])
marks = np.array([
65, 72, 88, 55, 92
])
fig, ax = plt.subplots(figsize=(8, 5))
ax.bar(students, marks)
ax.set_title("Student Performance")
ax.set_xlabel("Students")
ax.set_ylabel("Marks")
ax.set_ylim(0, 100)
ax.grid(axis='y')
plt.show()
Output
A professional student-performance bar chart is displayed with:
- Student names on the X-axis
- Marks on the Y-axis
- Title
- Grid lines
- Y-axis range from 0 to 100
Summary
In this tutorial, we learned the fundamentals of Matplotlib and how it can be used to
visualize numerical and categorical data.
- Installing Matplotlib
- Importing
matplotlib.pyplot
- Creating line plots
- Adding titles and labels
- Using markers and line styles
- Creating multiple lines
- Adding legends and grids
- Creating bar charts
- Creating horizontal bar charts
- Creating scatter plots
- Creating histograms
- Creating pie charts
- Creating subplots
- Using Figure and Axes
- Changing figure size
- Saving graphs
- Using Matplotlib with NumPy
- Visualizing student and sales data
Created by Bijan Krishna Paul
Computer Science • Python • Data Science