Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 16

A simple guide to matplotlib

01/06/2022 1
1. Anaconda individual edition
Anaconda Individual Edition is the world’s most popular Python distribution platform with over 25 million users
worldwide. You can trust in our long-term commitment to supporting the Anaconda open-source ecosystem, the platform of
choice for Python data science. It is the toolkit that equips you to work with thousands of open-source packages and
libraries.
Get installers here:
Anaconda | Individual Edition

01/06/2022 2
2. Jupyter notebook
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live
code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation,
statistical modeling, data visualization, machine learning, and much more.

01/06/2022 3
3. numpy
This is a quick overview of arrays in NumPy. It demonstrates how n-dimensional (n>=2) arrays are represented and can be
manipulated. In particular, if you don’t know how to apply common functions to n-dimensional arrays (without using for-
loops), or if you want to understand axis and shape properties for n-dimensional arrays, this article might be of help.
Learning Objectives
After reading, you should be able to:
Understand the difference between one-, two- and n-dimensional arrays in NumPy;
Understand how to apply some linear algebra operations to n-dimensional arrays without using for-loops;
Understand axis and shape properties for n-dimensional arrays.

01/06/2022 4
3. numpy
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all
of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.

For example, the coordinates of a point in 3D space [1, 2, 1] has one axis. That axis has 3 elements in it, so we say
it has a length of 3. In the example pictured below, the array has 2 axes. The first axis has a length of 2, the second
axis has a length of 3.

[[1., 0., 0.],


[0., 1., 2.]]

01/06/2022 5
3. numpy
NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as
the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less
functionality. The more important attributes of an ndarray object are:

ndarray.ndim-the number of axes (dimensions) of the array.


ndarray.shape-the dimensions of the array. This is a tuple of integers indicating the size of the array in each
dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is
therefore the number of axes, ndim.
ndarray.size-the total number of elements of the array. This is equal to the product of the elements of shape.
ndarray.dtype-an object describing the type of the elements in the array. One can create or specify dtype’s using
standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and
numpy.float64 are some examples.
ndarray.itemsize-the size in bytes of each element of the array. For example, an array of elements of type float64
has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to
ndarray.dtype.itemsize.
ndarray.data-the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute
because we will access the elements in an array using indexing facilities.

01/06/2022 6
4. Array Creation
There are several ways to create arrays. For example, you can create an array from a regular Python list or tuple
using the array function. The type of the resulting array is deduced from the type of the elements in the sequences
import numpy as np
a = np.array([2, 3, 4])
Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several
functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an
expensive operation.
The function zeros creates an array full of zeros, the function ones creates an array full of ones, and the function
empty creates an array whose initial content is random and depends on the state of the memory. By default, the
dtype of the created array is float64, but it can be specified via the key word argument dtype.
np.zeros((3, 4))
np.ones((2, 3, 4)
np.empty((2, 3))

01/06/2022 7
4. Array Creation
To create sequences of numbers, NumPy provides the arange function which is analogous to the Python built-in
range, but returns an array.
np.arange(10, 30, 5)
When arange is used with floating point arguments, it is generally not possible to predict the number of elements
obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace
that receives as an argument the number of elements that we want, instead of the step.
np.linspace(0, 2, 9) # 9 numbers from 0 to 2

01/06/2022 8
5. Basic Operations
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result.
a = np.array([20, 30, 40, 50])
b = np.arange(4) # array([0, 1, 2, 3])
c = a - b #array([20, 29, 38, 47])
Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The matrix
product can be performed using the @ operator (in python >=3.5) or the dot function or method.
A = np.array([[1, 1],
[0, 1]])
B = np.array([[2, 0],
[3, 4]])
A * B # elementwise product
A @ B # matrix product
A.dot(B) # another matrix product

01/06/2022 9
6. Matplotlib
These tutorials cover the basics of creating visualizations with Matplotlib, as well as some best-practices in using the
package effectively.

import matplotlib.pyplot as plt


import numpy as np

01/06/2022 10
7. A simple example
Matplotlib graphs your data on Figures (i.e., windows, Jupyter widgets, etc.), each of which can contain one or more Axes
(i.e., an area where points can be specified in terms of x-y coordinates, or theta-r in a polar plot, or x-y-z in a 3D plot, etc.).
The simplest way of creating a figure with an axes is using pyplot.subplots. We can then use Axes.plot to draw some data on
the axes:
fig, ax = plt.subplots() # Create a figure containing a single axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes.

01/06/2022 11
7. A simple example
Many other plotting libraries or languages do not require you to explicitly create an axes. In fact, you can do the same in
Matplotlib: for each Axes graphing method, there is a corresponding function in the matplotlib.pyplot module that performs
that plot on the "current" axes, creating that axes (and its parent figure) if they don't exist yet. So, the previous example can
be written more shortly as:

plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Matplotlib plot

01/06/2022 12
8. Parts of a figure
Now, let's have a deeper look at the components of a Matplotlib figure.

01/06/2022 13
9. Create a new figure
The easiest way to create a new figure is with pyplot:

fig = plt.figure() # an empty figure with no Axes


fig, ax = plt.subplots() # a figure with a single Axes
fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes

01/06/2022 14
10. Set title,label and legend

x = np.linspace(0, 2, 100) #Sample 100 values from [0,2] uniformly

fig, ax = plt.subplots() # Create a figure and an axes.


ax.plot(x, x, label='linear') # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic') # Plot more data on the axes...
ax.plot(x, x**3, label='cubic') # ... and some more.
ax.set_xlabel('x label') # Add an x-label to the axes.
ax.set_ylabel('y label') # Add a y-label to the axes.
ax.set_title("Simple Plot") # Add a title to the axes.
ax.legend() # Add a legend.

01/06/2022 15
11. subfigure
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 2, 1)
plt.plot(x1, y1, 'o-')
plt.subplot(2, 2, 2)
plt.plot(x2, y2, '.-')
plt.subplot(2, 2, 3)
plt.plot(x1, y1, 'o-')
plt.subplot(2, 2, 4)
plt.plot(x2, y2, '.-')
plt.show()

01/06/2022 16

You might also like