Introduction to Python — Day 3/3

Sudh Bhoi
5 min readMay 25, 2020

--

< Day 2: Structured Types

This would be a great example of leveraging an existing library (module), rather than writing procedures from scratch. Here, we want to explore the idea of using existing library procedures to guide processing and exploration of data.

Using Pylab

To import library into computing environment

import pylab as plt
  • This allows you to reference any library procedure as
plt.<procName>

It provides access to existing set of graphing/plotting procedures. Here, we’ll just see some simple examples; lots of additional information is available in documentation available with pylab.

Simple Example

This basic function plots 2 lists as x and y values.

Let 2 lists be of same length: xList and yList. To generate a plot, call

plt.plot(xList, yList)

Consider the following code snippet that generates x and y values:

mySamples = []
myLinear = []
myQuadratic = []
myCubic = []
myExponential = []
for i in range(0, 30):
mySamples.append(i)
myLinear.append(i)
myQuadratic.append(i**2)
myCubic.append(i**3)
myExponential.append(1.5**i)

Suppose you want to display all the of the graphs of the different orders of growth. You’d just call:

plt.plot(mySamples, myLinear)
plt.plot(mySamples, myQuadratic)
plt.plot(mySamples, myCubic)
plt.plot(mySamples, myExponential)

This is not very helpful as you can’t really see anything but the biggest of the plots because the scales are so different.

To graph each one separately, call

plt.figure(<arg>)         # <arg> gives name to the figure
  • It creates new display with that name if one doesn’t exist.
  • If a display with that name already exists, it reopens it for processing.
plt.figure(‘lin’)
plt.plot(mySamples, myLinear)
plt.figure(‘quad’)
plt.plot(mySamples, myQuadratic)

Providing Labels

plt.figure(‘lin’)
plt.xlabel(‘sample points’)
plt.ylabel(‘linear function’)
plt.figure(‘quad’)
plt.ylabel(‘quadratic function’)

Note that you must make the figure active before invoking the labels.

Adding Titles

plt.figure(‘lin’)
plt.title(‘Linear’)
plt.figure(‘quad’)
plt.title(‘Quadratic’)

Cleaning up windows

To reuse previously created display window, you need to clear it before drawing.

plt.figure(‘lin’)
plt.clf()

Comparing Results

Suppose you had to compare different plots, in particular, when the scales on the graphs are very different.

  • One of the options is to explicitly set limits the axis or axes.
plt.figure(‘lin’)
plt.clf()
plt.ylim(0,1000)
plt.plot(mySamples, myLinear)
plt.figure(‘quad’)
plt.clf()
plt.ylim(0,1000)
plt.plot(mySamples, myQuadratic)
plt.figure(‘lin’)
plt.title(‘Linear’)
plt.figure(‘quad’)
plt.title(‘Quadratic’)
  • The another option is to plot multiple functions on the same display.
plt.figure(‘lin quad’)
plt.clf()
plt.plot(mySamples, myLinear)
plt.plot(mySamples, myQuadratic)
plt.figure(‘cube exp’)
plt.clf()
plt.plot(mySamples, myCubic)
plt.plot(mySamples, myExponential)
plt.figure(‘lin quad’)
plt.title(‘Linear vs. Quadratic’)
plt.figure(‘cube exp’)
plt.title(‘Cubic vs. Exponential’)

Adding more documentation

plt.figure(‘lin quad’)
plt.clf()
plt.plot(mySamples, myLinear, label = ‘linear’)
plt.plot(mySamples, myQuadratic, label = ‘quadratic’)
plt.legend(loc = ‘upper left’)
plt.title(‘Linear vs. Quadratic’)
plt.figure(‘cube exp’)
plt.clf()
plt.plot(mySamples, myCubic, label = ‘cubic’)
plt.plot(mySamples, myExponential, label = ‘exponential’)
plt.legend()
plt.title(‘Cubic vs. Exponential’)

Controlling display parameters

Now suppose you want to control details of the display themselves like change colour of datasets, change width of line or displays, or using subplots.

  • Changing colour of datasets
plt.figure(‘lin quad’)
plt.clf()
plt.plot(mySamples, myLinear, ‘b-’, label = ‘linear’)
plt.plot(mySamples, myQuadratic,’ro’, label = ‘quadratic’)
plt.legend(loc = ‘upper left’)
plt.title(‘Linear vs. Quadratic’)
plt.figure(‘cube exp’)
plt.clf()
plt.plot(mySamples, myCubic, ‘g^’, label = ‘cubic’)
plt.plot(mySamples, myExponential, ‘r-‘,label = ‘exponential’)
plt.legend()
plt.title(‘Cubic vs. Exponential’)

Note that the highlighted string specifies colour and style. See documentation for choices of colour and style.

  • Changing width of lines
plt.figure(‘lin quad’)
plt.clf()
plt.plot(mySamples, myLinear, ‘b-’, label = ‘linear’, linewidth = 2.0)
plt.plot(mySamples, myQuadratic,’r’, label = ‘quadratic’, linewidth = 3.0)
plt.legend(loc = ‘upper left’)
plt.title(‘Linear vs. Quadratic’)
plt.figure(‘cube exp’)
plt.clf()
plt.plot(mySamples, myCubic, ‘g-‘, label = ‘cubic’, linewidth = 4.0)
plt.plot(mySamples, myExponential, ‘r’,label = ‘exponential’, linewidth = 5.0)
plt.legend()
plt.title(‘Cubic vs. Exponential’)
  • Using subplots
plt.figure(‘lin quad’)
plt.clf()
plt.subplot(211)
plt.ylimit(0, 900)
plt.plot(mySamples, myLinear, ‘b-’, label = ‘linear’, linewidth = 2.0)
plt.subplot(212)
plt.ylimit(0, 900)
plt.plot(mySamples, myQuadratic, ‘r’, label = ‘quadratic’, linewidth = 3.0)
plt.legend(loc = ‘upper left’)
plt.title(‘Linear vs. Quadratic’)
plt.figure(‘cube exp’)
plt.clf()
plt.subplot(121)
plt.ylim(0, 140000)
plt.plot(mySamples, myCubic, ‘g-‘, label = ‘cubic’, linewidth = 4.0)
plt.subplot(122)
plt.ylim(0, 140000)
plt.plot(mySamples, myExponential, ‘r’,label = ‘exponential’, linewidth = 5.0)
plt.legend()
plt.title(‘Cubic vs. Exponential’)

Note that in subplot() the numbers (from left to right) correspond to number of rows, number of columns, and location in terms of the display respectively.

Changing Scales

plt.figure(‘cube exp log’)
plt.clf()
plt.plot(mySamples, myCubic, ‘g-‘, label = ‘cubic’, linewidth = 2.0)
plt.plot(mySamples, myExponential, ‘r’,label = ‘exponential’, linewidth = 4.0)
plt.yscale(‘log’)
plt.legend()
plt.title(‘Cubic vs. Exponential’)
plt.figure(‘cube exp linear’)
plt.clf()
plt.plot(mySamples, myCubic, ‘g-‘, label = ‘cubic’, linewidth = 2.0)
plt.plot(mySamples, myExponential, ‘r’,label = ‘exponential’, linewidth = 4.0)
plt.legend()
plt.title(‘Cubic vs. Exponential’)

Programming Assignment

Question 0

Write a program that plots the graphs for linear, quadratic, cubic and exponential function. Use all the functions mentioned in the reading assignment for Day 3.

Question 1

Write a program to visualise (using plotting) your planning for retirement! If you intend to save an amount m every month and expect to earn a percentage r of income on investments each month.

Write a program that helps you explore how big a retirement fund will be compounded by the time you are ready to retire.

Your program should constitute of 3 functions:

  • displayRetireWMonthlies() — plots result vs monthly savings
  • displayRetireWRates() — plots result vs rates
  • displayRetireWBoth() — plots result vs both (monthly savings and rates)

Question 2 (Python Extras)

  1. Write a program that accepts a file name from the user, reads the file (if opened) and appends the data onto a list. Use try block (to open the file), except block (to check for IOError), else block (to read file if opened), and finally block (to close the file).
  2. Write a function to find average of grades entered. Use assert statement to raise an AssertionError except if assumption not met.
  3. Write a program that prints each character in each command line argument. (Hint: import sys)

⭐️ Congratulations on completing all the 3 Days of ‘Introduction to Python’!

I got introduced to the language through the MITx: 6.00.1x — ‘Introduction to Computer Science and Programming Using Python’ by Prof. Eric Grimson. This 3 Day Series is highly inspired from that course.

--

--