Basic plotting using matplotlib
First we'll discuss basic plotting of functions in python.
Then we'll go on to some applications of MAT 105 to advanced material in the CS major.
How do you do I/O in python?
How do you define a function in python?
How do you plot a function in python?
I/O in python
Input is how you get information into a program. Output is how information comes back into the real world.
One way to get information into a program is simply to hard code it like this:
The simplest way to get information out of a program in python is to use the print()
command.
Let's warm up by doing these two things together.
Advanced input
It's useful to be able to hard code constants into a program, but there are other kinds of input.
User input
File input
Command line input
Let's get some user input in the next cell.
Advanced output
Just printing numbers to the screen is kind of boring. We can make fancier output by using "formatting".
This lets your program incorporate variable values into output statements.
Representing functions
Now that we can do a little bit of I/O let's work on printing some functions.
But how do you represent a function in python?
There are lots of ways.
For plotting it's useful to represent a function as
A list of numbers in the domain
A list of corresponding numbers in the range
Remember that the domain of a function is the set of inputs and the range is the set of outputs.
Let's do a quick example.
The above code describes a little bit of the function .
You might notice that it's only defined at a few numbers, whereas really has as its domain.
But computers are finite machines and you always have to be satisfied with some finite description of any mathematical object.
Later we'll see how to add more details.
On to plotting!
The first think to do is to import the plotting library matplotlib.
Most plotting in python is done through the pyplot object.
Here we'll be calling it plt
for short.
It can do all kinds of things.
Let's make a simple plot of .
That was easy, right?
We just made a crude graph of .
Over the next few cells we'll improve the plot by adding
a title
a legend
enriching the domain and range
First let's add a title.
Again, that was very easy. We were even a little fancy because we used inside our title.
That's why we had to use "r" and the dollar signs.
If you don't care about how the plot looks you could leave those parts out.
Adding a legend
Now let's see how to add a legend to the plot.
A legend isn't very interesting unless there is more than one curve.
So at the same time we add the legend, we'll also add a plot of .
That looks pretty nice!
By the way, if you'd rather plot points than lines, you can easily do that.
Here's how. We just change plot
to scatter
in the code we had before.
Scatterplots can be very useful for representing data.
Smoothing out the curve
That was fun, but the curve is a little rough looking. It's also a lot of work to type out the domain and the range.
Is there a better way to do that?
Yes, definitely. It uses a powerful library called "numpy" which is short for Numerical Python.
Getting the domain
Like we said before, the domain of any function is finite inside a computer.
But we should be able to still get a lot of resolution.
Numpy let's us do that.
One way is to use the arange
command which returns a list of numbers between two given values.
Below we're going to get a list of numbers between 0 and 5 which are each separated by a distance of 0.1.
This will greatly increase the resolution of our plot. We could smooth things out even more by making step
smaller.
This improves the domain, but what about the range? Do we have to manually square all of these numbers?
No!
To define the range, we used a trick called broadcasting.
This means you apparently do something to a list, but it actually gets done to each member of the list.
By "squaring" the domain, we actually produced a list of each domain element, squared.
We could have cubed the elements the same way.
Let's revisit our plot.
That's starting to look pretty professional!
Polynomials
What if you want to plot something more complex, like a quadratic polynomial?
Broadcasting works with all kinds of arithmetic operations.
Let's plot a function of the form .
This time instead of writing "dom" I'm going to use the name x
for the same thing.
Python doesn't care what you name your variables -- I'm just doing it for convenience.
Similarly I'll now use y
for the range.
Notice that the line
seems to be defining a single value y
, but it's actually working with lists through the magic of broadcasting.
Adding user input
It might be fun to come back to our old idea of getting input from the user.
Then you can easily let the user decide which quadratic to plot.
Because user input is always understood to be a "string" (aka words) we need to convert to type "float" so that the system understands the input as numbers, not words.
Making a real application
You might know from physics class that if you throw an object up or down in a vacuum then the height of the object seconds later is given by the function
where is the initial velocity (in m/s) and is the initial height (in m).
Let's make a short program that gets and from the user, and shows them how the object will move.
In the code I use the quadratic formula to find when the object lands.
We also use some new options, like showing a grid and annotating the and axes.
Another application: compound interest
You might know that if you invest dollars at an annual interest rate of percent, and the investment compounds times per year, then the value of the investment after years is given by the function
Let's make a simple app that helps an investor visualize their returns.
Stock market investing
In some cases you may not know the average annual rate of return.
Let's do a version that shows the user a range of possibilities, depending on how the market does.
Visualizing complex arithmetic
Earlier in the semester you learned about complex numbers.
Each complex number has a real part and an imaginary part.
Python supports complex numbers. You use "j" to indicate the complex part of the number.
As you know you can add, subtract, multiply and divide complex numbers.
Let's try that out in python.
The complex plane
Any complex number can be thought of as a point in the complex plane.
Let's write a simple script to plot a complex number.
Visualizing complex arithmetic
You might know that arithmetic on complex numbers has a geometric meaning.
Let's make a graphic that illustrates this.
First we'll do addition.
Complex multiplication
Now we'll visualize complex multiplication. Note that the length of the product is the product of the lengths, and the argument of the product is the sum of the arguments.
Complex exponents
Because of the way complex products work, exponentiating a complex number causes it to "spiral"...