Lecture 5
In summary:
Matplotlib can be installed via conda:
or with pip:
Remember! You can install packages in ipython REPL/juypter notebook by inserting a ‘!’ to the beginning of a shell command.
First, we will import the matplotlib module. The plotting function is located within the pyplot
package within matplotlib. The use of this package is so common that 99% of Python users will alias this import as plt
:
With this package now imported, we can now use the plot
function. To begin with, let’s just plot a simple line chart. In this case, the plot
function takes an x
and y
argument, where x
denotes the values along the x-axis and y
are the values along the y-axis.
In this example, we have created two vectors. The first x
, creates a vector of 100 values from -10 to 10. y
is the sin function applied to x
. Finally, in the third line, we plot the sin wave using these two vectors.
There are many different types of plots that one can make using matplotlib. These include the most popular:
We’re going to take a look at how we create each type of plot, examining what type of inputs they require.
We’ve already seen one example of a line plot. This plot draws a line between each x,y point. For instance in the previous example, we created a sin wave by ‘sampling’ such wave using 100 samples from -10 to 10. Let’s see what happens when we sample only 10 points:
We see the results are a less than ideal representation of a sin wave as plot
will simply draw a straight line from each point.
If we want to see where each sample of the sin wave is, we could use instead the scatter plot, which will (by default) place a small circle at every x,y value. To create a scatter plot, we use scatter
instead of the plot
function. The arguments to this function are the same, however.
Now we can see the position of each individual sample from the sin wave. If we, once again, sample 100 points from this curve, we will see better results.
Bar plots are a simple plot that again takes an x
and a y
, where x is the numerical position of the bar’s centre, and y
is the height of the bar.
Histograms allow us to visualise the distribution of values. In matplotlib, we can create a histogram of a vector by using the hist
function that takes only the vector as its argument.
Box plots also allow us to visualise the distribution, but the distribution of values within a group. In this example we’re visualising the distribution of 3 groups. Using the boxplot
function, we pass a matrix.
In matplotlib, we can plot an ‘image’ – that is a 2D matrix – using the imshow
function. For example:
Of course, given the name, we can then use imshow
to plot an image as well, as long as we have the image loaded as a 2D array of values.
3 dimensional plots require us to import another module from matplotlib.
After importing this module, we can using the projection=“3d” and carry on plotting as normal.
There are many more different types of plots you can make using matplotlib. You can find a comprehensive list at:
What if we wanted to create many plots side-by-side? For this we can use the subplots
function. This function takes the number of rows, and number of columns to create. It returns two values, the first is the figure (entire figure), and the second value is a list of sub figures. Using this list, we can place a plot of each of them.
Or we could put them onto the same plot. Matplotlib will automatically give them a different colour. If we use the label
argument to plot
, we can also give them a name that will appear when we call legend()
.
We can change the position of the legend by specifying a different integer value for the loc
argument (or string values such as ‘upper left’, ‘upper right’, …). Additionally, we can change the number of columns the legend has with the ncol
argument.
You can find the API reference for the different arguments to legend at: https://matplotlib.org/stable/api/legend_api.html?highlight=legend#module-matplotlib.legend
Good graphs always have their axis’s labelled. To do this in matplotlib, if we have a subplot object, we use set_xlabel
, or we can use plt.xlabel(...)
. Here is an example with an subplot object:
A common change you may want to make to your figure is to change its size or aspect ratio. figure()
or subplots()
take an optional argument called figsize
. This argument expects a tuple representing the width and height of the figure in inches.
<Figure size 768x240 with 0 Axes>
Here we are creating a figure with 8 inches of width, and 2.5 inches of height.
This is especially useful when you have many sub-figures, as by default, they will be ‘squashed’ into the default aspect ratio. We can ‘give them more space’ by modifying this figsize
argument when creating the many sub-figures.
When creating a plot, there are many different properties you can change. Some of these include:
There are also some properties for the markers, i.e. the circles in the scatter plot. These properties are:
If this example we are modifying some of the line properties that include the color (c), setting it to a string value of “green”. The linewidth (lw) to be thicker, and making the line to be a dotted line by specifying the linestyle (ls) to “=–={”.
When we create a heatmap using imshow
, the gradients of colour are automatically set. Yet, we can control the colour gradient using a colour map. First we must import cm
from matplotlib:
Then we can get a colour map with 10 levels using get_cmap
:
You can find a full list of different colour maps at: https://matplotlib.org/stable/tutorials/colors/colormaps.html
Now that we have our new colour maps, we can pass it as an cmap
argument when we create a plot.
If we want to customise the numbers along each axis, we use the set_xticks
for the x-axis and set_yticks
for the y-axis. These functions take the list of locations for each ‘tick’, and optionally a list of labels to use instead of the numbers.
In all of the previous plots, the background has no grids, they are simply white. If we wanted to add grid lines to the plot we use the .grid()
method. This function, by default, adds the major grid lines.
The default behaviour of matplotlib is to plot using a linear scale. In certain situations, we want view the plot using a different scale. For this we can use set_yscale
.
By default, matplotlib will calculate the minimum and maximum values of the data, and use those values to set the limits of the plot. Using set_xlim
and set_ylim
we can change this default behaviour.
We can annotate our plot in a number of way:
Sometimes you will want to display multiple sub-plots on the same plot, but where each have a very different range in values. Instead of having a single y-axis, with twinx()
we can create a two y-axis plot.
There are many many more types of plots you can create with matplotlib. I would recommend that you read the documentation to fully appreciate everything that it can visualise: