Matplotlib Exercises
Many thanks to the following people for contributing to these exercises: William Hunter
Here is an exercise to practice plotting with matplotlib
. Your aim is to reproduce the figures as provided.
Follow the tasks outline below and ask for help whenever you need it! Good luck!
Firstly, remember to import numpy
and matplotlib
so that you can use them!
import numpy as np
import matplotlib.pyplot as plt
We will also define our x
, y
, and z
arrays to be plotted.
resolution = 1000
x = np.linspace(0, 50, resolution)
y = np.sin(x)
z = np.exp(y)
Task 1
Let’s do this one together! Plot y
against x
and call this figure 1.
plt.figure(1)
plt.plot(x, y)
plt.show()
Task 2
Add a title to this graph, call this figure 2, make the title ‘My Graph’.
Task 3
Add x and y labels to your graph, call this figure 3, make the y axis called ‘Amplitude (W)’ and the x axis called ‘time (s)’
Task 4
Plot y AND z against x on the same graph!
Task 5
Make the y plot the colour ‘Blue’ and the z plot the colour ‘Red’
Hint - watch out for the British (correct) spelling of Colour and the American (incorrect) spelling of Color.
Python only accepts the incorrect spelling…
Task 6
Add a legend onto the graph to make sure you can tell which is y and z
Task 7
Restrict the y scale to a range of -0.5 to 2.0
Task 8
Save the file as a high resolution .png
file.
Task 9
Code up your favourite mathematical function - and plot it for all your friends to see!! If you don’t have a favourite, I am fond of \(y = x \times exp(-x)\)… 😁
Task 10
Congratulate yourself, you have learnt all the basics of matplotlib plotting 😀
The full solutions and code to this lab will be posted after the lab is completed so you can check everything!
Josiah’s bonus challenge task
Try creating multiple subplots on a single Figure.
Hint: Check out plt.subplots()
or plt.subplot()
.