# Knowledge Base/Python/matplotlib

## A simple XY plot (procedural approach)

Code:

import math

import matplotlib.pyplot

import numpy

xs = numpy.arange(-math.pi, math.pi, 0.1)
ys1 = numpy.sin(xs)
ys2 = numpy.cos(xs)

matplotlib.pyplot.plot(xs, ys1, "r-", lw=2)
matplotlib.pyplot.plot(xs, ys2, "g-", lw=2)
matplotlib.pyplot.xlabel("$x$")
matplotlib.pyplot.ylabel("$y$")
matplotlib.pyplot.title("Trigonometric functions: $\\sin$ and $\\cos$")
matplotlib.pyplot.grid(True)
matplotlib.pyplot.legend(("$\\sin(x)$", "$\\cos(x)$"))

matplotlib.pyplot.show()

## A simple XY plot (procedural approach; emulating MATLAB)

We can use Python namespaces in a different way to emulate MATLAB.

Code:

import math

import numpy

from pylab import *

xs = numpy.arange(-math.pi, math.pi, 0.1)
ys1 = numpy.sin(xs)
ys2 = numpy.cos(xs)

plot(xs, ys1, "r-", lw=2)
plot(xs, ys2, "g-", lw=2)
xlabel("$x$")
ylabel("$y$")
title("Trigonometric functions: $\\sin$ and $\\cos$")
grid(True)
legend(("$\\sin(x)$", "$\\cos(x)$"))

show()

## A simple XY plot (object-oriented approach)

Code:

import math

import matplotlib.pyplot

import numpy

xs = numpy.arange(-math.pi, math.pi, 0.1)
ys1 = numpy.sin(xs)
ys2 = numpy.cos(xs)

figure = matplotlib.pyplot.figure(figsize=(8.0, 5.0))
# The size of the figure is specified as (width, height) in inches

axes = figure.add_axes([0.1, 0.25, 0.8, 0.65])
# [left, bottom, width, height], all the quantities are fractions of figure
# width and height

axes.grid(True)

plot1 = axes.plot(xs, ys1, "r-", lw=2)
plot2 = axes.plot(xs, ys2, "g-", lw=2)

axes.set_title("Trigonometric functions: $\\sin$ and $\\cos$")

axes.set_xlabel("$x$")
axes.set_ylabel("$y$")

figure.legend((plot1, plot2), ("$\\sin(x)$", "$\\cos(x)$"), 'lower center')
# This is a *figure* legend, so it can appear outside the axes

# Or you could use an axes legend, within the axes:
# axes.legend((plot1, plot2), ("$\\sin(x)$", "$\\cos(x)$"), 'lower center')

matplotlib.pyplot.show()

## Saving figures

In the previous example, replace

matplotlib.pyplot.show()

with

figure.savefig("foo.eps", format="eps")

to save the figure as an EPS image instead of showing it (of course, you could do both).

You could also save it as a transparent PNG (among other things):

figure.savefig("foo.png", format="png", transparent=True)

To save the image in a file with the same base file name but a different extension, you can use something like this:

import os
import sys

# Save the figure in a file with the same name as the script, in the same
# directory, but with an appropriate file extension
scriptFilePathName = os.path.abspath(sys.argv[0])
scriptDirPathName = os.path.dirname(scriptFilePathName)
scriptFileBaseName = os.path.basename(scriptFilePathName)
scriptFileBaseNameNoExt = os.path.splitext(scriptFileBaseName)[0]
epsFileBaseName = scriptFileBaseNameNoExt + ".eps"
epsFilePathName = os.path.join(scriptDirPathName, epsFileBaseName)
figure.savefig(epsFilePathName, format="eps")