Numpy and Matplotlib

This lecture will introduce NumPy and Matplotlib. These are two of the most fundamental parts of the scientific python “ecosystem”. Most everything else is built on top of them.

Numpy: The fundamental package for scientific computing with Python

Matlotlib: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.

Importing and Examining a New Package

This will be our first experience with importing a package which is not part of the Python standard library.

import numpy as np

What did we just do? We imported a package. This brings new variables (mostly functions) into our interpreter. We access them as follows.

# find out what is in our namespace
# find out what's in numpy
# find out what version we have

There is no way we could explicitly teach each of these functions. The numpy documentation is crucial!


The core class is the numpy ndarray (n-dimensional array).

The main difference between a numpy array an a more general data container such as list are the following:

  • Numpy arrays can have N dimensions (while lists, tuples, etc. only have 1)

  • Numpy arrays hold values of the same datatype (e.g. int, float), while lists can contain anything.

  • Numpy optimizes numerical operations on arrays. Numpy is fast!

from IPython.display import Image
# create an array from a list
a = np.array([9,0,2,1,0])
# find out the datatype
# find out the shape
# what is the shape
# another array with a different datatype and shape
b = np.array([[5,3,1,9],[9,2,3,0]], dtype=np.float64)

# check dtype and shape
b.dtype, b.shape
(dtype('float64'), (2, 4))


The fastest varying dimension is the last dimension! The outer level of the hierarchy is the first dimension. (This is called “c-style” indexing)

Array Creation

There are lots of ways to create arrays.

# create some uniform arrays
c = np.zeros((9,9))
d = np.ones((3,6,3), dtype=np.complex128)
e = np.full((3,3), np.pi)
e = np.ones_like(c)
f = np.zeros_like(d)

arange works very similar to range, but it populates the array “eagerly” (i.e. immediately), rather than generating the values upon iteration.

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

arange is left inclusive, right exclusive, just like range, but also works with floating-point numbers.

array([2.  , 2.25, 2.5 , 2.75, 3.  , 3.25, 3.5 , 3.75])

A frequent need is to generate an array of N numbers, evenly spaced between two values. That is what linspace is for.

array([2.        , 2.10526316, 2.21052632, 2.31578947, 2.42105263,
       2.52631579, 2.63157895, 2.73684211, 2.84210526, 2.94736842,
       3.05263158, 3.15789474, 3.26315789, 3.36842105, 3.47368421,
       3.57894737, 3.68421053, 3.78947368, 3.89473684, 4.        ])
# log spaced
array([ 10.        ,  12.91549665,  16.68100537,  21.5443469 ,
        27.82559402,  35.93813664,  46.41588834,  59.94842503,
        77.42636827, 100.        ])

Numpy also has some utilities for helping us generate multi-dimensional arrays. meshgrid creates 2D arrays out of a combination of 1D arrays.

x = np.linspace(-2*np.pi, 2*np.pi, 100)
y = np.linspace(-np.pi, np.pi, 50)
xx, yy = np.meshgrid(x, y)
xx.shape, yy.shape
((50, 100), (50, 100))


Basic indexing is similar to lists

# get some individual elements of xx
xx[0,0], xx[-1,-1], xx[3,-5]
(-6.283185307179586, 6.283185307179586, 5.775453161144872)
# get some whole rows and columns
xx[0].shape, xx[:,-1].shape
((100,), (50,))
# get some ranges
(7, 10)

There are many advanced ways to index arrays. You can read about them in the manual. Here is one example.

# use a boolean array as an index
idx = xx<0
# the array got flattened

Visualizing Arrays with Matplotlib

It can be hard to work with big arrays without actually seeing anything with our eyes! We will now bring in Matplotib to start visualizating these arrays. For now we will just skim the surface of Matplotlib. Much more depth will be provided in the next chapter.

from matplotlib import pyplot as plt

For plotting a 1D array as a line, we use the plot command.

[<matplotlib.lines.Line2D at 0x7efecaf6f3a0>]

There are many ways to visualize 2D data. He we use pcolormesh.

<matplotlib.collections.QuadMesh at 0x7efecae663a0>
<matplotlib.collections.QuadMesh at 0x7efecadce9a0>

Array Operations

There are a huge number of operations available on arrays. All the familiar arithemtic operators are applied on an element-by-element basis.

Basic Math

f = np.sin(xx) * np.cos(0.5*yy)
<matplotlib.collections.QuadMesh at 0x7efecada8df0>

Manipulating array dimensions

Swapping the dimension order is accomplished by calling transpose.

f_transposed = f.transpose()
<matplotlib.collections.QuadMesh at 0x7efecad14130>

We can also manually change the shape of an array…as long as the new shape has the same number of elements.

g = np.reshape(f, (8,9))
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_442/ in <module>
----> 1 g = np.reshape(f, (8,9))

<__array_function__ internals> in reshape(*args, **kwargs)

/srv/conda/envs/notebook/lib/python3.8/site-packages/numpy/core/ in reshape(a, newshape, order)
    296            [5, 6]])
    297     """
--> 298     return _wrapfunc(a, 'reshape', newshape, order=order)

/srv/conda/envs/notebook/lib/python3.8/site-packages/numpy/core/ in _wrapfunc(obj, method, *args, **kwds)
     56     try:
---> 57         return bound(*args, **kwds)
     58     except TypeError:
     59         # A TypeError occurs if the object does have such a method in its

ValueError: cannot reshape array of size 5000 into shape (8,9)

However, be careful with reshapeing data! You can accidentally lose the structure of the data.

g = np.reshape(f, (200,25))
<matplotlib.collections.QuadMesh at 0x7efecac11c70>

We can also “tile” an array to repeat it many times.

f_tiled = np.tile(f,(3, 2))
<matplotlib.collections.QuadMesh at 0x7efecab78250>

Another common need is to add an extra dimension to an array. This can be accomplished via indexing with None.

x[None, :].shape
(1, 100)
x[None, :, None, None].shape
(1, 100, 1, 1)


Not all the arrays we want to work with will have the same size. One approach would be to manually “expand” our arrays to all be the same size, e.g. using tile. Broadcasting is a more efficient way to multiply arrays of different sizes Numpy has specific rules for how broadcasting works. These can be confusing but are worth learning if you plan to work with Numpy data a lot.

The core concept of broadcasting is telling Numpy which dimensions are supposed to line up with each other.


Dimensions are automatically aligned starting with the last dimension. If the last two dimensions have the same length, then the two arrays can be broadcast.

print(f.shape, x.shape)
g = f * x
(50, 100) (100,)
(50, 100)
<matplotlib.collections.QuadMesh at 0x7efecabed310>

However, if the last two dimensions are not the same, Numpy cannot just automatically figure it out.

# multiply f by y
print(f.shape, y.shape)
h = f * y
(50, 100) (50,)
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_442/ in <module>
      1 # multiply f by y
      2 print(f.shape, y.shape)
----> 3 h = f * y

ValueError: operands could not be broadcast together with shapes (50,100) (50,) 

We can help numpy by adding an extra dimension to y at the end. Then the length-50 dimensions will line up.

print(f.shape, y[:, None].shape)
h = f * y[:, None]
(50, 100) (50, 1)
(50, 100)
<matplotlib.collections.QuadMesh at 0x7efecaabaee0>

Reduction Operations

In scientific data analysis, we usually start with a lot of data and want to reduce it down in order to make plots of summary tables. Operations that reduce the size of numpy arrays are called “reductions”. There are many different reduction operations. Here we will look at some of the most common ones.

# sum
# mean
# standard deviation

A key property of numpy reductions is the ability to operate on just one axis.

# apply on just one axis
g_ymean = g.mean(axis=0)
g_xmean = g.mean(axis=1)
plt.plot(x, g_ymean)
[<matplotlib.lines.Line2D at 0x7efecaa9b790>]
plt.plot(g_xmean, y)
[<matplotlib.lines.Line2D at 0x7efecaa00610>]

Data Files

It can be useful to save numpy data into files.'g.npy', g)


Numpy .npy files are a convenient way to store temporary data, but they are not considered a robust archival format. Later we will learn about NetCDF, the recommended way to store earth and environmental data.

g_loaded = np.load('g.npy')

np.testing.assert_equal(g, g_loaded)