Skip to content
Laviyx Learn

Try

Python Lab · Experiment 35

Explore NumPy, SciPy and Matplotlib

PythonWeek 8JNTUH R22 · CS206ES

Aim

To install the NumPy, SciPy and Matplotlib packages with pip, and to write a Python program that explores their main features: NumPy arrays, shapes, arithmetic and statistics; SciPy statistics, integration and equation solving; and a Matplotlib line plot saved as an image file.

Algorithm

  1. Install the packages once from the command prompt: pip install numpy scipy matplotlib.
  2. Import numpy as np, the stats, integrate and optimize modules of scipy, and matplotlib.pyplot as plt (after choosing the Agg backend, which draws into files).
  3. NumPy: create a one-dimensional array and a 2 × 3 array, print their shape, size and number of dimensions, and make arrays with arange, linspace and zeros.
  4. NumPy: do element-wise arithmetic, find the sum, mean, maximum and standard deviation, and do matrix operations (transpose, product, determinant, inverse) on a 2 × 2 matrix.
  5. SciPy: find the mode of a list of marks and a normal-distribution probability with scipy.stats, the integral of x² from 0 to 3 with integrate.quad, and the root of x² − 2 = 0 with optimize.brentq.
  6. Matplotlib: plot sin x and cos x for x from 0 to 2π, add a title, axis labels, a legend and a grid, and save the plot to plot.png with plt.savefig.
  7. Print the results of each step, rounded so the output is easy to read.

Program

Python
import numpy as np
from scipy import stats, integrate, optimize
import matplotlib
matplotlib.use("Agg")  # draw into image files, no window
import matplotlib.pyplot as plt

np.set_printoptions(precision=3, suppress=True)

print("===== NumPy =====")
a = np.array([10, 20, 30, 40, 50])
print("Array a:", a)
print("Shape:", a.shape, " Size:", a.size, " Dimensions:", a.ndim)

m = np.array([[1, 2, 3], [4, 5, 6]])
print("2-D array m:")
print(m)
print("Shape of m:", m.shape)
print("m reshaped to 3 x 2:")
print(m.reshape(3, 2))

print("arange(0, 10, 2):", np.arange(0, 10, 2))
print("linspace(0, 1, 5):", np.linspace(0, 1, 5))
print("zeros((2, 3)):")
print(np.zeros((2, 3)))

print("a + 5 :", a + 5)
print("a * 2 :", a * 2)
print("a ** 2:", a ** 2)
print("Sum:", a.sum(), " Mean:", a.mean(), " Max:", a.max())
print("Standard deviation:", round(float(a.std()), 3))

x = np.array([[4, 7], [2, 6]])
print("Matrix x:")
print(x)
print("Transpose of x:")
print(x.T)
print("x @ x (matrix product):")
print(x @ x)
print("Determinant of x:", round(float(np.linalg.det(x)), 3))
print("Inverse of x:")
print(np.linalg.inv(x))

print("\n===== SciPy =====")
marks = [56, 67, 72, 81, 67, 90]
print("Marks:", marks)
print("Mode of marks:", int(stats.mode(marks).mode))
print("Median of marks:", float(np.median(marks)))
print("P(Z < 1.96) for the standard normal:", round(float(stats.norm.cdf(1.96)), 4))

area, error = integrate.quad(lambda t: t ** 2, 0, 3)
print("Integral of x^2 from 0 to 3:", round(area, 4))

root = optimize.brentq(lambda t: t ** 2 - 2, 0, 2)
print("Root of x^2 - 2 = 0 between 0 and 2:", round(root, 4))

print("\n===== Matplotlib =====")
t = np.linspace(0, 2 * np.pi, 100)
plt.plot(t, np.sin(t), label="sin x")
plt.plot(t, np.cos(t), label="cos x")
plt.title("sin x and cos x")
plt.xlabel("x (radians)")
plt.ylabel("value")
plt.legend()
plt.grid(True)
plt.savefig("plot.png")
print("Plot saved to plot.png")

Output

Output
===== NumPy =====
Array a: [10 20 30 40 50]
Shape: (5,)  Size: 5  Dimensions: 1
2-D array m:
[[1 2 3]
 [4 5 6]]
Shape of m: (2, 3)
m reshaped to 3 x 2:
[[1 2]
 [3 4]
 [5 6]]
arange(0, 10, 2): [0 2 4 6 8]
linspace(0, 1, 5): [0.   0.25 0.5  0.75 1.  ]
zeros((2, 3)):
[[0. 0. 0.]
 [0. 0. 0.]]
a + 5 : [15 25 35 45 55]
a * 2 : [ 20  40  60  80 100]
a ** 2: [ 100  400  900 1600 2500]
Sum: 150  Mean: 30.0  Max: 50
Standard deviation: 14.142
Matrix x:
[[4 7]
 [2 6]]
Transpose of x:
[[4 2]
 [7 6]]
x @ x (matrix product):
[[30 70]
 [20 50]]
Determinant of x: 10.0
Inverse of x:
[[ 0.6 -0.7]
 [-0.2  0.4]]

===== SciPy =====
Marks: [56, 67, 72, 81, 67, 90]
Mode of marks: 67
Median of marks: 69.5
P(Z < 1.96) for the standard normal: 0.975
Integral of x^2 from 0 to 3: 9.0
Root of x^2 - 2 = 0 between 0 and 2: 1.4142

===== Matplotlib =====
Plot saved to plot.png

Recorded by running this exact program.

How it works

The syllabus says "Plotpy"; this program reads that as Matplotlib's pyplot module, the usual Python plotting tool.

Installing the packages. NumPy, SciPy and Matplotlib are not part of Python's standard library. Install them once from the command prompt (Windows) or terminal (Linux):

Text
pip install numpy scipy matplotlib

If pip is not found, use python -m pip install numpy scipy matplotlib (or python3 -m pip ... on Linux). Check an installation with pip show numpy, or in Python with import numpy; print(numpy.__version__).

What each library is for. NumPy gives the fast ndarray type for numbers and maths on whole arrays at once. SciPy is built on NumPy and adds scientific tools: statistics (scipy.stats), integration (scipy.integrate), equation solving and optimization (scipy.optimize), and more. Matplotlib draws graphs.

Checking the output. The standard deviation of 10, 20, 30, 40, 50 is √((400 + 100 + 0 + 100 + 400) / 5) = √200 ≈ 14.142 (std divides by n by default). The determinant of x is 4 × 6 − 7 × 2 = 10, and its inverse is (1/10) × [[6, −7], [−2, 4]]. The integral of x² from 0 to 3 is 3³ / 3 = 9, and the root of x² − 2 = 0 is √2 ≈ 1.4142.

The plot. matplotlib.use("Agg") makes Matplotlib draw into image files without opening a window, and plt.savefig("plot.png") writes the graph to plot.png in the current folder. The image shows two curves from 0 to 2π: a blue sin x curve starting at 0 and an orange cos x curve starting at 1, with the title, axis labels, a legend and a grid. On your own computer you can leave out the two matplotlib lines at the top and call plt.show() at the end to see the graph in a window instead.

np.set_printoptions(precision=3, suppress=True) prints array values with at most 3 decimal places and without scientific notation.

Common mistakes

  • Naming your own file numpy.py, scipy.py or matplotlib.py. Python then imports your file instead of the library and fails with confusing errors. Rename the file and delete any __pycache__ folder next to it.

  • Running pip install inside the Python prompt (>>>). pip is a command for the command prompt or terminal, not Python code.

  • Using * for matrix multiplication of NumPy arrays. x * x multiplies element by element; the matrix product is x @ x or np.dot(x, x).

  • Calling plt.savefig after plt.show(). Once the window is closed the figure is cleared, so the saved image is blank. Save first, then show.

Viva questions

Try to answer each one aloud before you open it.

  • What is NumPy, and why is a NumPy array faster than a Python list for maths?

    NumPy is a library for numerical computing. Its array stores values of one type in a single block of memory, and operations like a * 2 run as compiled code on the whole array at once instead of a Python loop over each item.

  • What do shape, ndim and size tell you about an array?

    shape is a tuple of the length along each dimension, such as (2, 3); ndim is the number of dimensions; size is the total number of elements.

  • What is the difference between arange and linspace?

    np.arange(start, stop, step) uses a step size and leaves out stop. np.linspace(start, stop, num) gives num evenly spaced values and includes stop.

  • Name some modules of SciPy and what they do.

    scipy.stats for statistics and probability distributions, scipy.integrate for integration, scipy.optimize for finding roots and minimums, and scipy.linalg for linear algebra.

  • What is pyplot in Matplotlib?

    matplotlib.pyplot is Matplotlib's module of simple plotting functions such as plot, title, xlabel, legend, savefig and show. It is usually imported as plt.

  • How do you install a package with pip?

    Run pip install package-name in the command prompt or terminal, for example pip install numpy. pip list shows the installed packages.

Learn the concepts

All Python Programming Lab experiments →