Lecture 13 - Plotting in Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Lecture 13 - Plotting in Python

The following will be covered in this lecture:

1. Introduction to modules - how to import them


2. Very basic examples from numpy module
3. Using matplotlib module for graphs

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 import a module, simply type: import module_name .

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.

In [ ]: from math import pi


print(round(pi, 2))

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.

Example: Try to find the square root of a list of numbers.

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.

Exercise: Use linspace to set up an array starting at 0, ending at 5 with 20 steps.

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

# Generate x values from -10 to 10


x = np.linspace(-10, 10, 100)

# Calculate y values (quadratic function y = x^2)


y = x**2

# Plot the quadratic function


plt.plot(x, y)

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')

# Display the plot


plt.grid(True)
plt.show()

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:

In [ ]: import matplotlib.pyplot as plt


import numpy as np

fig, ax = plt.figure(), plt.axes()

f = lambda x: np.sin(x) + 0.5 * np.sin(4 * x)


g = lambda x: np.cos(x)
X = np.linspace(-np.pi, 3 * np.pi, 100)

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)

h(x) = sin(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 [ ]:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy