Python Graph Plotting

I needed to plot some dates and values and embed them in an HTML email.  The result for the plotting part was this little Python script.  The script is fairly trivial, with some comments inline.  The gist is as follows:

  • Get a dictionary of keys and values, where the keys are dates that are parsable by dateutil.parser.
  • Turn the dictionary into two arrays; one containing dates sorted into order, the other containing the matching values (put into appropriate order for the dates).
  • Pass the two arrays into the plotting function that calls matplotlib, which then saves the graph.
  • Lastly, use the system verb ‘open’ to open the graph image in the default image viewer.

You’ll need Python 2.6, http://matplotlib.sourceforge.net/ and http://numpy.scipy.org/

import matplotlib
import matplotlib.pyplot as plt
import pylab
import dateutil
import os

#  Install matplotlib and numpy to get this to work

def dict_to_dates_and_values(data):
    dates = []
    values = []

    #  ensure the data is sorted by date, i.e. dict key
    sorted_keys = data.keys()
    sorted_keys.sort()
    for key in sorted_keys:
        #  parse date to system date object
        dates.append(dateutil.parser.parse(key))
        values.append(int(data[key]))

    return (dates, values)

def plot_graph(xtitle, ytitle, dates, values, filename):
    plt.plot_date(pylab.date2num(dates), values, linestyle = '-')
    plt.ylabel(ytitle, fontsize='xx-small')
    plt.xlabel(xtitle, fontsize='xx-small')
    plt.xticks(fontsize='xx-small')
    plt.yticks(fontsize='xx-small')
    current_figure = plt.gcf()
    current_axes = plt.gca()
    #  Set number of x axis ticks
    current_axes.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(4))
    #  Set figure size
    current_figure.set_size_inches(5,3)
    #  Save a png
    current_figure.savefig(filename, bbox_inches='tight')

data = dict()
data["2010-01-01"] = 1
data["2010-01-02"] = 2
data["2010-01-03"] = 4
data["2010-01-04"] = 8
data["2010-01-05"] = 16
data["2010-01-06"] = 32

(dates, values) = dict_to_dates_and_values(data)

xtitle = "Dates"
ytitle = "Values"
filename = "test.png"

plot_graph(xtitle, ytitle, dates, values, filename)

#  Use system verb and open the png in the default viewer.
os.startfile(filename, 'open')