*(For more resources related to this topic, see here.)*

# Installing matplotlib

Before experimenting with matplotlib, you need to install it. Here we introduce some tips to get matplotlib up and running without too much trouble.

## How to do it...

We have three likely scenarios: you might be using Linux, OS X, or Windows.

**Linux**

Most Linux distributions have Python installed by default, and provide matplotlib in their standard package list. So all you have to do is use the package manager of your distribution to install matplotlib automatically. In addition to matplotlib, we highly recommend that you install NumPy, SciPy, and SymPy, as they are supposed to work together. The following list consists of commands to enable the default packages available in different versions of Linux:

**Ubuntu**: The default Python packages are compiled for Python 2.7. In a command terminal, enter the following command:

**sudo apt-get install python-matplotlib python-numpy python-scipy python-sympy****ArchLinux**: The default Python packages are compiled for Python 3. In a command terminal, enter the following command:

**sudo pacman -S python-matplotlib python-numpy python-scipy python-sympy**If you prefer using Python 2.7, replace python by python2 in the package names

**Fedora**: The default Python packages are compiled for Python 2.7. In a command terminal, enter the following command:

**sudo yum install python-matplotlib numpy scipy sympy**

*There are other ways to install these packages; in this article, we propose the most simple and seamless ways to do it.*

**Windows and OS X**

Windows and OS X do not have a standard package system for software installation. We have two options—using a ready-made self-installing package or compiling matplotlib from the code source. The second option involves much more work; it is worth the effort to have the latest, bleeding edge version of matplotlib installed. Therefore, in most cases, using a ready-made package is a more pragmatic choice.

You have several choices for ready-made packages: Anaconda, Enthought Canopy, Algorete Loopy, and more! All these packages provide Python, SciPy, NumPy, matplotlib, and more (a text editor and fancy interactive shells) in one go. Indeed, all these systems install their own package manager and from there you install/uninstall additional packages as you would do on a typical Linux distribution. For the sake of brevity, we will provide instructions only for Enthought Canopy. All the other systems have extensive documentation online, so installing them should not be too much of a problem.

So, let's install Enthought Canopy by performing the following steps:

- Download the Enthought Canopy installer from https://www.enthought.com/products/canopy. You can choose the free Express edition. The website can guess your operating system and propose the right installer for you.
- Run the Enthought Canopy installer. You do not need to be an administrator to install the package if you do not want to share the installed software with other users.
- When installing, just click on
**Next**to keep the defaults. You can find additional information about the installation process at http://docs.enthought.com/canopy/quick-start.html.

That's it! You will have Python 2.7, NumPy, SciPy, and matplotlib installed and ready to run.

# Plotting one curve

The initial example of Hello World! for a plotting software is often about showing a simple curve. We will keep up with that tradition. It will also give you a rough idea about how matplotlib works.

## Getting ready

You need to have Python (either v2.7 or v3) and matplotlib installed. You also need to have a text editor (any text editor will do) and a command terminal to type and run commands.

## How to do it...

Let's get started with one of the most common and basic graph that any plotting software offers—**curves**. In a text file saved as plot.py, we have the following code:

import matplotlib.pyplot as plt X = range(100) Y = [value ** 2 for value in X] plt.plot(X, Y) plt.show()

Assuming that you installed Python and matplotlib, you can now use Python to interpret this script. If you are not familiar with Python, this is indeed a Python script we have there! In a command terminal, run the script in the directory where you saved plot.py with the following command:

python plot.py

Doing so will open a window as shown in the following screenshot:

The window shows the curve Y = X ** 2 with X in the [0, 99] range. As you might have noticed, the window has several icons, some of which are as follows:

- : This icon opens a dialog, allowing you to save the graph as a picture file. You can save it as a bitmap picture or a vector picture.
- : This icon allows you to translate and scale the graphics. Click on it and then move the mouse over the graph. Clicking on the left button of the mouse will translate the graph according to the mouse movements. Clicking on the right button of the mouse will modify the scale of the graphics.
- : This icon will restore the graph to its initial state, canceling any translation or scaling you might have applied before.

## How it works...

Assuming that you are not very familiar with Python yet, let's analyze the script demonstrated earlier.

The first line tells Python that we are using the matplotlib.pyplot module. To save on a bit of typing, we make the name plt equivalent to matplotlib.pyplot. This is a very common practice that you will see in matplotlib code.

The second line creates a list named X, with all the integer values from 0 to 99. The range function is used to generate consecutive numbers. You can run the interactive Python interpreter and type the command range(100) if you use Python 2, or the command list(range(100)) if you use Python 3. This will display the list of all the integer values from 0 to 99. In both versions, sum(range(100)) will compute the sum of the integers from 0 to 99.

The third line creates a list named Y, with all the values from the list X squared. Building a new list by applying a function to each member of another list is a Python idiom, named **list comprehension**. The list Y will contain the squared values of the list X in the same order. So Y will contain 0, 1, 4, 9, 16, 25, and so on.

The fourth line plots a curve, where the x coordinates of the curve's points are given in the list X, and the y coordinates of the curve's points are given in the list Y. Note that the names of the lists can be anything you like.

The last line shows a result, which you will see on the window while running the script.

## There's more...

So what we have learned so far? Unlike plotting packages like gnuplot, matplotlib is not a command interpreter specialized for the purpose of plotting. Unlike Matlab, matplotlib is not an integrated environment for plotting either. matplotlib is a Python module for plotting. Figures are described with Python scripts, relying on a (fairly large) set of functions provided by matplotlib.

Thus, the philosophy behind matplotlib is to take advantage of an existing language, Python. The rationale is that Python is a complete, well-designed, general purpose programming language. Combining matplotlib with other packages does not involve tricks and hacks, just Python code. This is because there are numerous packages for Python for pretty much any task. For instance, to plot data stored in a database, you would use a database package to read the data and feed it to matplotlib. To generate a large batch of statistical graphics, you would use a scientific computing package such as SciPy and Python's I/O modules.

Thus, unlike many plotting packages, matplotlib is very orthogonal—it does plotting and only plotting. If you want to read inputs from a file or do some simple intermediary calculations, you will have to use Python modules and some glue code to make it happen. Fortunately, Python is a very popular language, easy to master and with a large user base. Little by little, we will demonstrate the power of this approach.

# Using NumPy

NumPy is not required to use matplotlib. However, many matplotlib tricks, code samples, and examples use NumPy. A short introduction to NumPy usage will tell you the reason.

## Getting ready

Along with having Python and matplotlib installed, you also have NumPy installed. You have a text editor and a command terminal.

## How to do it...

Let's plot another curve, sin(x), with x in the [0, 2 * pi] interval. The only difference with the preceding script is the part where we generate the point coordinates. Type and save the following script as sin-1.py:

import math import matplotlib.pyplot as plt T = range(100) X = [(2 * math.pi * t) / len(T) for t in T] Y = [math.sin(value) for value in X] plt.plot(X, Y) plt.show()

Then, type and save the following script as sin-2.py:

import numpy as np import matplotlib.pyplot as plt X = np.linspace(0, 2 * np.pi, 100) Y = np.sin(X) plt.plot(X, Y) plt.show()

Running either sin-1.py or sin-2.py will show the following graph exactly:

## How it works...

The first script, sin-1.py, generates the coordinates for a sinusoid using only Python's standard library. The following points describe the steps we performed in the script earlier:

- We created a list T with numbers from 0 to 99—our curve will be drawn with 100 points.
- We computed the x coordinates by simply rescaling the values stored in T so that x goes from 0 to 2 pi (the range() built-in function can only generate integer values).
- As in the first example, we generated the y coordinates.

The second script sin-2.py, does exactly the same job as sin-1.py—the results are identical. However, sin-2.py is slightly shorter and easier to read since it uses the NumPy package.

*NumPy is a Python package for scientific computing. matplotlib can work without NumPy, but using NumPy will save you lots of time and effort. The NumPy package provides a powerful multidimensional array object and a host of functions to manipulate it.*

**The NumPy package**

In sin-2.py, the X list is now a one-dimensional NumPy array with 100 evenly spaced values between 0 and 2 pi. This is the purpose of the function numpy.linspace. This is arguably more convenient than computing as we did in sin-1.py. The Y list is also a one-dimensional NumPy array whose values are computed from the coordinates of X. NumPy functions work on whole arrays as they would work on a single value. Again, there is no need to compute those values explicitly one-by-one, as we did in sin-1.py. We have a shorter yet readable code compared to the pure Python version.

## There's more...

NumPy can perform operations on whole arrays at once, saving us much work when generating curve coordinates. Moreover, using NumPy will most likely lead to much faster code than the pure Python equivalent. Easier to read and faster code, what's not to like? The following is an example where we plot the binomial x^2 -2x +1 in the [-3,2] interval using 200 points:

import numpy as np import matplotlib.pyplot as plt X = np.linspace(-3, 2, 200) Y = X ** 2 - 2 * X + 1. plt.plot(X, Y) plt.show()

Running the preceding script will give us the result shown in the following graph:

Again, we could have done the plotting in pure Python, but it would arguably not be as easy to read. Although matplotlib can be used without NumPy, the two make for a powerful combination.

# Plotting multiple curves

One of the reasons we plot curves is to compare those curves. Are they matching? Where do they match? Where do they not match? Are they correlated? A graph can help to form a quick judgment for more thorough investigations.

## How to do it...

Let's show both sin(x) and cos(x) in the [0, 2pi] interval as follows:

import numpy as np import matplotlib.pyplot as plt X = np.linspace(0, 2 * np.pi, 100) Ya = np.sin(X) Yb = np.cos(X) plt.plot(X, Ya) plt.plot(X, Yb) plt.show()

The preceding script will give us the result shown in the following graph:

## How it works...

The two curves show up with a different color automatically picked up by matplotlib. We use one function call plt.plot() for one curve; thus, we have to call plt.plot() here twice. However, we still have to call plt.show() only once. The functions calls plt.plot(X, Ya) and plt.plot(X, Yb) can be seen as declarations of intentions. We want to link those two sets of points with a distinct curve for each.

matplotlib will simply keep note of this intention but will not plot anything yet. The plt.show() curve, however, will signal that we want to plot what we have described so far.

## There's more...

This **deferred rendering** mechanism is central to matplotlib. You can declare what you render as and when it suits you. The graph will be rendered only when you call plt.show(). To illustrate this, let's look at the following script, which renders a bell-shaped curve, and the slope of that curve for each of its points:

import numpy as np import matplotlib.pyplot as plt def plot_slope(X, Y): Xs = X[1:] - X[:-1] Ys = Y[1:] - Y[:-1] plt.plot(X[1:], Ys / Xs) X = np.linspace(-3, 3, 100) Y = np.exp(-X ** 2) plt.plot(X, Y) plot_slope(X, Y) plt.show()

The preceding script will produce the following graph:

One of the function call, plt.plot(), is done inside the plot_slope function, which does not have any influence on the rendering of the graph as plt.plot() simply declares what we want to render, but does not execute the rendering yet. This is very useful when writing scripts for complex graphics with a lot of curves. You can use all the features of a proper programming language—loop, function calls, and so on— to compose a graph.

# Plotting curves from file data

As explained earlier, matplotlib only handles plotting. If you want to plot data stored in a file, you will have to use Python code to read the file and extract the data you need.

## How to do it...

Let's assume that we have time series stored in a plain text file named my_data.txt as follows:

0 0 1 1 2 4 4 16 5 25 6 36

A minimalistic pure Python approach to read and plot that data would go as follows:

import matplotlib.pyplot as plt X, Y = [], [] for line in open('my_data.txt', 'r'): values = [float(s) for s in line.split()] X.append(values[0]) Y.append(values[1]) plt.plot(X, Y) plt.show()

This script, together with the data stored in my_data.txt, will produce the following graph:

## How it works...

The following are some explanations on how the preceding script works:

- The line X, Y = [], [] initializes the list of coordinates X and Y as empty lists.
- The line for line in open('my_data.txt', 'r') defines a loop that will iterate each line of the text file my_data.txt. On each iteration, the current line extracted from the text file is stored as a string in the variable line.
- The line values = [float(s) for s in line.split()] splits the current line around empty characters to form a string of tokens. Those tokens are then interpreted as floating point values. Those values are stored in the list values.
- Then, in the two next lines, X.append(values[0]) and Y.append(values[1]), the values stored in values are appended to the lists X and Y.

The following equivalent one-liner to read a text file may bring a smile to those more familiar with Python:

import matplotlib.pyplot as plt with open('my_data.txt', 'r') as f: X, Y = zip(*[[float(s) for s in line.split()] for line in f]) plt.plot(X, Y) plt.show()

## There's more...

In our data loading code, note that there is no serious checking or error handling going on. In any case, one might remember that a good programmer is a lazy programmer. Indeed, since NumPy is so often used with matplotlib, why not use it here? Run the following script to enable NumPy:

import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('my_data.txt') plt.plot(data[:,0], data[:,1]) plt.show()

This is as short as the one-liner shown in the preceding section, yet easier to read, and it will handle many error cases that our pure Python code does not handle. The following point describes the preceding script:

- The numpy.loadtxt() function reads a text file and returns a 2D array. With NumPy, 2D arrays are not a list of lists, they are true, full-blown matrices.
- The variable data is a NumPy 2D array, which give us the benefit of being able to manipulate rows and columns of a matrix as a 1D array. Indeed, in the line plt.plot(data[:,0], data[:,1]), we give the first column of data as x coordinates and the second column of data as y coordinates. This notation is specific to NumPy.

Along with making the code shorter and simpler, using NumPy brings additional advantages. For large files, using NumPy will be noticeably faster (the NumPy module is mostly written in C), and storing the whole dataset as a NumPy array can save memory as well. Finally, using NumPy allows you to support other common file formats (CVS and Matlab) for numerical data without much effort.

As a way to demonstrate all that we have seen so far, let's consider the following task. A file contains N columns of values, describing N–1 curves. The first column contains the x coordinates, the second column contains the y coordinates of the first curve, the third column contains the y coordinates of the second curve, and so on. We want to display those N–1 curves. We will do so by using the following code:

import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('my_data.txt') for column in data.T: plt.plot(data[:,0], column) plt.show()

The file my_data.txt should contain the following content:

0 0 6 1 1 5 2 4 4 4 16 3 5 25 2 6 36 1

Then we get the following graph:

We did the job with little effort by exploiting two tricks. In NumPy notation, data.T is a transposed view of the 2D array data—rows are seen as columns and columns are seen as rows. Also, we can iterate over the rows of a multidimensional array by doing for row in data. Thus, doing for column in data.T will iterate over the columns of an array. With a few lines of code, we have a fairly general plotting generic script.

# Plotting points

When displaying a curve, we implicitly assume that one point follows another—our data is the time series. Of course, this does not always have to be the case. One point of the data can be independent from the other. A simple way to represent such kind of data is to simply show the points without linking them.

## How to do it...

The following script displays 1024 points whose coordinates are drawn randomly from the [0,1] interval:

import numpy as np import matplotlib.pyplot as plt data = np.random.rand(1024, 2) plt.scatter(data[:,0], data[:,1]) plt.show()

The preceding script will produce the following graph:

## How it works...

The function plt.scatter() works exactly like plt.plot(), taking the x and y coordinates of points as input parameters. However, each point is simply shown with one marker. Don't be fooled by this simplicity—plt.scatter() is a rich command. By playing with its many optional parameters, we can achieve many different effects.

# Summary

In this article we learned the basics of working with matplotlib. The basic figure types are introduced in this article with minimal examples.

## Resources for Article:

**Further resources on this subject:**

- Advanced Matplotlib: Part 1 [Article]
- Advanced Matplotlib: Part 2 [Article]
- Plotting Data with Sage [Article]