Lecture 13 - Plotting in Python
Lecture 13 - Plotting in Python
Lecture 13 - Plotting in Python
Source: Python Primer Chapter 14, Section 16.1, 16.2 and 17.1
Importing Modules ¶
There are various modules which can be imported into Python and used in your project. These modules are
libraries with pre-defined functions which can be used to make your life easier than having to write everything
yourself.
To use (call) a function from the module, type module_name.function() , where the arguements (if any),
are included as needed. If you need information on the different functions in a module, you can use dir . For
example, we can call the directory for math :
In [ ]: import math
dir(math)
Recall that you can also use help to get the docstring of a function - this includes the functions inside
imported modules.
In [ ]:
Often, we may only want a specific function or functions from a module, say, func_1, func_2. Then we may
type: from module_name import func_1, func_2 .
In this case, we need only call the functions by their names, func_1 and func_2. (Since we imported them
specifically, Python knows now that when we use the name of that function it is the one from that module.)
For example, the following code imports the math module and then uses the number π , called by using
math.pi .
In [ ]: import math
p=math.pi
print(p)
print(round(p, 2))
The following code imports pi from math, so only "pi" needs to be typed.
It is possible to import a module and give it a name easier for you to use: import long_module_name as
name .
For example, we can import the math module but refer to it as "m". (Note that it is not the convention to do
this for math . You will see why this is useful later.)
In [ ]: import math as m
print(round(m.pi, 2))
Lastly, at times we may want to import everything from a module and simply call the function by its name,
rather than module_name.function . To do this use: from module_name import * .
–
Exercise: Try this way of importing and then use the sqrt function to find √2.
In [ ]:
Numpy module
The numpy module is used when we need to work with vectors or matrices. In order to plot graphs, we need
arrays (vectors / sequence of numbers) and we usually want to do calculations on them.
In [ ]:
This will not work if you use math - it is made for single numbers. Now let's try to use the numpy module.
(The conventional name to import numpy as is "np".)
In [ ]: import numpy as np
Even though this works for a normal list, there is a better (more efficient in memory and speed) way to work
with vectors. These are called arrays in numpy.
In [ ]: x=np.array([1,2,3])
You can also set up an array by using linspace . This is very useful to set up a vector with evenly spaced
values, without having to type it all (or do a for loop). If we use np.linspace(start,stop,num) , it will
create an array that starts at start, ends at end and has num entries.
Note: This is not the same as with range where the last value is not included.
In [ ]:
Plotting
The standardly used module for plotting in Python is matplotlib . Moreover, matplotlib.pyplot is
used.
The standard name to import matplotlib.pyplot is "plt".\ Often, when plotting, the numpy module is also
used so that calculations can be performed on arrays/vectors by Python to create plots.
Note: It is advisable to use the standard naming conventions as when you search for assistance on the
internet, your help will be presented using the standard naming convention.
Now, consider the following very basic code to sketch the graph of y = x
2
.
In [ ]: import numpy as np
import matplotlib.pyplot as plt
We can add information on the figure. These things are not necessary, but makes it look nice.
In [ ]: # Add labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot of Quadratic Function')
When we are doing multiple things on one graph or using different graphs, it is better to initialize the figure
and axes first. When we plot, we then specify that we want to plot on the axes that we created. Work through
the following code:
ax.plot(X, f(X))
ax.plot(X, g(X))
plt.show()
Exercise: Plot the following functions on the same graph within the domain [−2π, 2π] :
f (x) = sin(x)
g(x) = cos(x)
Extra challenge: Customize the appearance of the plot by adding labels to the x-axis and y-axis, a title, and a
legend to differentiate between the functions. Use different line styles and colors for each function to make
them visually distinct.
In [ ]: