Skip to content

Latest commit

 

History

History
174 lines (80 loc) · 3.97 KB

File metadata and controls

174 lines (80 loc) · 3.97 KB

← previous - home - next →

Table of contents

Visualising data using matplotlib

We will not look at 3D plots!

In this course we will look at how to plot data using matplotlib. The following cheatsheets will be quite useful, for the class and for later. Also, I used a lot the following book to prepare this course together with the original matplotlib manual.

You are strongly advised to have a look at these links for the course.

In this course, we will have a look at usual line plots, box plots, violin plots, scatter plots and how to make animations.

1. Loading the necessary libraries


The first step is to import matplotlib and its main class pyplot

import matplotlib as mpl
import matplotlib.pyplot as plt

Then, we can use a special matplotlib command:

%matplotlib inline

to be able to easily visualize the plot in our notebook.

Note that it is not necessary to run that line in all browsers. Moreover, you can use the following line:

%matplotlib notebook

It gives more freedom with the plots but I personally like it less since it puts the focus on the figure and requires more steps to go back to the code.

%matplotlib inline

2. Line plots


Now that we are set up, let's create our first plot.

But first, we need to create the data that we will want to plot:

import numpy as np
Y = np.sin(np.linspace(-np.pi, 2*np.pi, 30))

We can then plot the line that we created the following way:

plt.plot(Y)
[<matplotlib.lines.Line2D at 0x10fda0e20>]

png

We are plotting what we want but, the x values are not the correct ones (in $[0, 30]$ instead of $[-\pi, 2\pi]$).

The reason is that we are only giving the y axis values (note that they are indeed ranging in $[-1, 1]$). So let's give the x values:

X = np.linspace(-np.pi, 2*np.pi, 30)
Y = np.sin(X)
plt.plot(X, Y)
[<matplotlib.lines.Line2D at 0x10ff973d0>]

png

Matplotlib, by default, shows us such data as blue lines between data points. We can change that and show only the measured points in red:

plt.plot(X, Y, marker='o', linestyle='', color='red')
[<matplotlib.lines.Line2D at 0x11e80f220>]

png

You can find all the different kind of markers, line styles and colours in the cheatsheet mentioned before.

Moreover, matplotlib is "nice" and, because the marker, linestyle and colour are properties that are often changed they allow an easier way to modify them:

plt.plot(X, Y, 'or')
[<matplotlib.lines.Line2D at 0x11e87ef20>]

png

plt.plot(X, Y, 'b-.>')
[<matplotlib.lines.Line2D at 0x11e8e2aa0>]

png

← previous - home - next →