Plotting Graphs with Python


Contents

Overview

The plotting libraries we use in the lectures are simple wrappers around a relatively standard python plotting library called matplotlib. So to plot using the functions we used in lectures (outside Udacity's classroom, i.e., offline, in your own computer), you will need both matplotlib and the wrapper functions.

Installing matplotlib is similar to installing other Python modules: pip install matplotlib. If you don't have pip, this provides instructions to install it.

As to the wrapper, the code below should work on your local machine much as the example code you saw in lectures. Feel free to use it directly and as a starting point for experimenting with matplotlib. As you experiment, feel free to post your questions in the discussion forums.

Installation Instructions

Ready-made Distributions

These python distributions already include matplotlib:

General Instructions

Python 2.7 is highly recommended due to other versions not being supported by one or more of matplotlib dependencies. You'll need to install numpy and matplotlib to plot graphs with Python.

Linux Ubuntu and Debian

From the terminal run the following command:

$ sudo apt-get install python-numpy python-matplotlib

Windows XP

Specific instructions for a few popular Python distributions follow:

Active State

From the Windows command prompt (cmd) run the following command:

C:\> pypm install numpy
C:\> pypm install matplotlib

Python Software Foundation

  • Download numpy from here and run the installer.
  • Download matplotlib from here and run the installer.

If easy_install is installed (it should be, pip comes with most Python distributions), you may also install numpy and matplotlib by running the following commands on Windows cmd:

C:\> pip numpy
C:\> pip matplotlib

Windows 7/8 64-bit

Download and install the following packages (in this order):

Mac OS X

The easiest way is to install Anaconda, but the general instructions (use pip) should work.

ST101 (Introduction to Statistics) Wrapper

Source Code

File Name: plotting.py

from matplotlib import pyplot
from numpy import arange
import bisect

def scatterplot(x,y):
    pyplot.plot(x,y,'b.')
    pyplot.xlim(min(x)-1,max(x)+1)
    pyplot.ylim(min(y)-1,max(y)+1)
    pyplot.show()

def barplot(labels,data):
    pos=arange(len(data))
    pyplot.xticks(pos+0.4,labels)
    pyplot.bar(pos,data)
    pyplot.show()

def histplot(data,bins=None,nbins=5):
    minx,maxx=min(data),max(data)
    space=(maxx-minx)/float(nbins)
    if not bins: bins=arange(minx,maxx,space)
    binned=[bisect.bisect(bins,x) for x in data]
    l=['%.1f'%x for x in list(bins)+[maxx]] if space<1 else [str(int(x)) for x in list(bins)+[maxx]]
    displab=[x+'-'+y for x,y in zip(l[:-1],l[1:])]
    barplot(displab,[binned.count(x+1) for x in range(len(bins))])

def barchart(x,y,numbins=5):
    datarange=max(x)-min(x)
    bin_width=float(datarange)/numbins
    pos=min(x)
    bins=[0 for i in range(numbins+1)]

    for i in range(numbins):
        bins[i]=pos
        pos+=bin_width
    bins[numbins]=max(x)+1
    binsum=[0 for i in range(numbins)]
    bincount=[0 for i in range(numbins)]
    binaverage=[0 for i in range(numbins)]

    for i in range(numbins):
        for j in range(len(x)):
            if x[j]>=bins[i] and x[j]<bins[i+1]:
                bincount[i]+=1
                binsum[i]+=y[j]

    for i in range(numbins):
        binaverage[i]=float(binsum[i])/bincount[i]
    barplot(range(numbins),binaverage)

def piechart(labels,data):
    fig=pyplot.figure(figsize=(7,7))
    pyplot.pie(data,labels=labels,autopct='%1.2f%%')
    pyplot.show()

Using the Wrapper

To use the wrapper in your local environment, simply create a file named plotting.py, copy and paste the contents of the source code above to it and save it in your work directory (where you keep your Python code). Alternatively you can modify the PYTHONPATH environment variable of your O.S. to include the directory where the wrapper is located.

from plotting import *

barchart([1, 2, 3, 4, 5], [1, 2, 3, 4, 5], 5)

tmp6.png

CS222 (Differential Equations in Action) Wrapper

Source Code

File Name: udacityplots.py

import matplotlib, matplotlib.pyplot
import numpy
import types

def show_plot(arg1, arg2=None):

    def real_decorator(f):
        def wrapper(*args, **kwargs):
            matplotlib.pyplot.figure(figsize=(arg1, arg2))
            result = f(*args, **kwargs)
            matplotlib.pyplot.show()
            return result
        return wrapper

    if type(arg1) == types.FunctionType:
        f = arg1
        arg1, arg2 = 10, 5
        return real_decorator(f)
    return real_decorator

Using the Wrapper

To use the wrapper in your local environment, simply create a file named udacityplots.py, copy and paste the contents of the source code above to it and save it in your work directory (where you keep your Python code). Alternatively you can modify the PYTHONPATH environment variable of your O.S. to include the directory where the wrapper is located.

# SIMPLE
# Plots square root function from 0 to 100
import math
from udacityplots import *

@show_plot
def simple():
    x_data = numpy.linspace(0., 100., 1000)

    for x in x_data:
        y = math.sqrt(x)
        matplotlib.pyplot.scatter(x, y)

    axes = matplotlib.pyplot.gca()
    axes.set_xlabel('x')
    axes.set_ylabel('y')

simple()

image.png