How-to install Matplotlib and SciPy using Macports

by Carson Reynolds

Perhaps you have heard rumors that MATLAB with its ugly syntax and license management can be replaced by some Python libraries. This all sounds very enticing, but you cannot for the life of you figure out how to install these libraries from the modest wiki documentation.

Here you will find an explanation the process of installing and testing matplotlib and scipy using Macports. The advantage of using Macports over the SVN tree or someone’s binary is that management and upgrade of these libraries is more convenient down the line.

The first step will be to install XCode and Macports following their instructions. If you have already installed Macports and Python be sure to perform a selfupdate and upgrade of the Python packages to make sure you have the latest versions. Once Macports is installed we’re ready to start building the lengthy toolchain.

The second step is to install a series of ports using Macports. The following directions have been tested with Python 2.6 and previous Python versions (2.4-2.5). So, one by one, install the following ports:


sudo port install python26
sudo port install python_select
sudo python_select python26
sudo port install py26-wxpython py26-numpy py26-matplotlib
sudo port install py26-scipy py26-ipython

Depending on how fast your mac is, this might take hours. If you encounter errors and you had previously installed some of these libraries, as a first step try to upgrade them:


sudo port selfupdate
sudo port upgrade installed

If you were foolish enough to try to test the whole system at this point, when you tried to plot nothing would show up. If you tried to force plotting using show() you’d get some cryptic errors stating:

"Your currently selected backend, 'agg' does not support show()."

To get the plotting facility operating as expected a configuration file is needed: ~/.matplotlib/matplotlibrc. Edit this text file and add the following line:

backend : WXAgg # Use wxpython as the plotting backend.

At this point you’re ready for a quick test. Open up ipython:

ipython-2.6 -pylab

Next type in the following Python code:
import matplotlib.pyplot as plt
plt.plot([1,2,3])

If everything has proceeded as planned, what you ought to see a figure of a diagonal line.

the diagonal test plot

You may be interested in trying something more complex like this code which reproduces figure 1.2 from Bishop’s Pattern Recognition and Machine Learning:

import matplotlib
import numpy as np
import matplotlib.pylab as plt

x = np.linspace(-np.pi, np.pi, 10)
x1 = np.linspace(-np.pi, np.pi, 100)
y = np.sin(x)
y+= np.random.normal(0,0.3,size=x.shape)
y1 = np.sin(x1)
plt.plot(x, y, 'bo')
plt.plot(x1, y1, 'g')

a simularca of figure 1.2 from PRML

Update: now provides instructions for Python 2.6 after further testing.
Update: now provides instructions for Python 2.5 after feedback from Greg.