One of the most powerful reasons to use a computer for mathematics is the ability to visualise the problem. We might be able to solve a kinematics equation to find the trajectory of a projectile and get some equation like
$$\mathbf{r}(t) = v_0 \cos \alpha \mathbf{\underline{i}} + \left( v_0 \sin\alpha t - \frac{1}{2}gt^2 \right)\mathbf{\underline{j}}$$and perhaps, given the necessary parameters you could sketch the solution and have an idea of what traectory the particle follows. But with a computer we can plot the trajectory, and then play with it for different parameters, seeing how the motion changes. This ability to interact with the maths and have a tactile understanding of the mechanism it's describing is one of the invaluable abilities afforded us by computers.
Once again, we will be using one of python's many libraries to allow us to plot. This time the library is called pyplot, which is actually just a small part of a larger library called matplotlib. We import it, and the numpy library like this
import numpy as np
import matplotlib.pyplot as plt
Which names the plotting library as plt, just as we named the numpy library np.
So what can we plot? Quite often you will see questions which ask you to plot functions. This could get confusing because what you are plotting may be a mathematical function, but of course in python 'function' means something different. Python can only plot numbers. So to plot a single point with coordinates (0,0.5) we would execute
plt.plot(0,0.5,'.')
which tells python to put a dot ('.') at those particular coordinates.
More often, though, we will be plotting lots of points at once, in the form of arrays. What we are really doing is plotting lots of pairs of x and y values, and python will draw a connecting line for us. This is how we can go about plotting particular mathematical functions.
Let's make a simple graph of $y=\sin(x)$ for $0\leq x \leq 2\pi$. We need some $x$ values to use, so we'll use the np.linspace command to generate a grid of 100 linearly spaced points between $0$ and $2\pi$. Then we can use that array to calculate the $y$ values:
x=np.linspace(0,2*np.pi,100)
y=np.sin(x)
plt.plot(x,y)
plt.savefig("output.png")
Notice the final command- plt.savefig("output.png"). This creates a png file of the figure called 'output.png'. On repl.it this will allow you to view the figure, and also to download it to use in other places (which you will need to do for exercises later in the module).
We can go back and add things to the plot by editing the code. For instance, we could add a second line to our plot either by adding a second plot command like this
y=np.sin(x)
plt.plot(x,y)
z=np.cos(x) #additional line to be plotted
plt.plot(x,z) #additional plot command
or with a single plot command like this:
plt.plot(x,y,x,z)
In fact we can plot any number of data sets by passing them to the plot command in (X,Y) pairs as above.
You will notice that pyplot assigns default colours to the lines that are plotted. We can set the colour, and the line style too by passing our (X,Y) pairs with a format string like this
plt.plot(x,y,'ro') # plots y against x in red circles
plt.plot(x,y,'b-',x,z,'g--') # plots y in blue line and z in a green dashed line
There's a whole list of format strings you can use:
| character | color | $ $ | character | description | $ $ | character | description |
|---|---|---|---|---|---|---|---|
'b' |
blue | $ $ | '.' |
point marker | $ $ | '-' |
solid line style |
'g' |
green | $ $ | 'o' |
circle marker | $ $ | '--' |
dashed line style |
'r' |
red | $ $ | 's' |
square marker | $ $ | '-.' |
dash-dot line style |
'c' |
cyan | $ $ | '*' |
star marker | $ $ | ':' |
dotted line style |
'm' |
magenta | $ $ | '+' |
plus marker | $ $ | ||
'y' |
yellow | $ $ | 'x' |
x marker | $ $ | ||
'k' |
black | $ $ | 'D' |
diamond marker | $ $ |
You should always give your axes some sensible labels. You can do this like so:
plt.xlabel('x')
plt.ylabel('y')
plt.title('plot of sin(x)')
Sometimes you will want to set a particular scale for your axes too. You can do this using `plt.axis':
plt.axis( [-2, 2, -1, 1] )
where the four numbers in the square bracket are the lower and upper x and y values respectively.
Finally, the plots are always presented on a rectangular scale by default. But if you want $x$ and $y$ on the same scale (so that squares appear square and circles appear circular, for instance) use
plt.axis('equal')
It is always important when you are showing multiple data sets to distinguish them somehow. Of course, giving them different colours or linestyles is useful, but it doesn't actually tell you what is what. To add a legend to your plot you must label each data set as you plot it: like this
x=np.linspace(0,2*np.pi,100)
y=np.sin(x)
plt.plot(x,y,'g--',label='sin(x)') # Label first line
z=np.cos(x)
plt.plot(x,z,'b-', label='cos(x)') # Label second line
plt.xlabel('x')
plt.ylabel('y')
plt.legend() # Show the legend