By the end of this lab, you will be able to:
Understand what Matplotlib is and how it integrates with NumPy.
Create and customise visual plots using NumPy arrays.
Plot line graphs, scatter plots, bar charts, and histograms.
Practise plotting synthetic data created using NumPy.
Matplotlib is a Python library used for creating graphs and charts. It is especially powerful when used with NumPy arrays.
NumPy allows you to generate and manipulate numerical data efficiently.
Matplotlib takes that data and turns it into clear, informative visuals.
They work hand-in-hand in data science and machine learning workflows.
Before we can begin, we need to install and import the right tools.
pip install numpy matplotlib
import numpy as np
import matplotlib.pyplot as plt
We use np for NumPy and plt for Matplotlib—these are standard abbreviations used in the industry.
Let’s begin by plotting a simple line graph using NumPy data.
x and y are NumPy arrays.
Mathematical operations like x ** 2 are applied to each element of the array.
plt.plot() uses these arrays to draw the line graph.
We’ll now try different types of visualisations, all based on NumPy arrays.
Useful for showing the relationship between two variables.
np.random.rand() creates random values between 0 and 1.
Bar charts are used to compare quantities for categories.
Histograms show the distribution of a dataset.
Let’s make our plots more informative and attractive.
np.linspace() generates evenly spaced values.
Custom styles (color, linestyle, marker) improve readability.
plt.legend() labels the line for clarity when multiple lines are used.
Use NumPy arrays to complete the tasks below. Try to modify and experiment with the values.
Use np.arange() to create x = [0, 1, 2, ..., 10]
Let y = x ** 2
Plot x and y with a title, labels, and grid.
Generate two arrays of 100 random values each using np.random.rand(100).
Create a scatter plot of x vs y.
Create arrays for 5 categories and their values.
Plot them as a bar chart.
Generate 1000 random numbers from a normal distribution using np.random.randn(1000).
Plot a histogram with 25 bins.
Create two sets of y-values: y1 = np.sin(x) and y2 = np.cos(x).
Plot them on the same graph using plt.plot() twice.
Add a legend using plt.legend() to label each line.