Matplotlib

Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

We can produce specific types of figures such as bar charts, pie charts, histograms, scatter plots, etc.

These can be output in a range of formats (SVG / PDF / PNG).

In this section we'll cover the basics of producing plots. We'll show and customize a set of default properties that comes with matplotlib, colour, axis, labels, style, etc, and present a more elaborate cases that show how well matplotlib mingles with python.

First One of iPython Notebooks 'magic commands'. %matplotlib inline puts matplotlib into the cell output rather than creating a popup window.


In [1]:
%matplotlib inline

Libraries we will be using:


In [2]:
import numpy as np
import matplotlib.pyplot as plt

A basic matplotlib using Python's range function for data


In [3]:
plt.plot(range(20))


Out[3]:
[<matplotlib.lines.Line2D at 0xa4ea2e8>]

A scatter plot with using NumPy's random function to create data


In [4]:
N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()


A bar chart


In [5]:
y = np.random.rand(5)
x = np.arange(5)
plt.bar(x,y)
plt.show()


A scatter plot with colours, area and alpha blending


In [6]:
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2  # 0 to 15 point radiuses

plt.scatter(x, y, s=area, c=colors, alpha=0.5)

plt.colorbar()

plt.show()


Changing matplotlib default output

Basic plot


In [7]:
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

plt.plot(X,C)
plt.plot(X,S)

plt.show()


Setting the defaults explictily


In [ ]:
# Create a new subplot from a grid of 1x1
plt.subplot(111)

# Plot cosine using blue color with a continuous line of width 1 (pixels)
plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")

# Plot sine using green color with a continuous line of width 1 (pixels)
plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")

# Set x limits
plt.xlim(-4.0,4.0)

# Set x ticks
plt.xticks(np.linspace(-4,4,9,endpoint=True))

# Set y limits
plt.ylim(-1.0,1.0)

# Set y ticks
plt.yticks(np.linspace(-1,1,5,endpoint=True))

# Save figure using 72 dots per inch
# savefig("../exercice_2.png",dpi=72)

# Show result on screen
plt.show()

Increasing size, x y limits and change colours


In [ ]:
plt.figure(figsize=(10,6), dpi=80)
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-")
plt.show()

Set tick values and Latex


In [ ]:
plt.figure(figsize=(10,6), dpi=80)
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], 
           [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.yticks([-1, 0, +1],
           [r'$-1$', r'$0$', r'$+1$'])
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-")
plt.show()

Label Plot and Axis


In [ ]:
plt.figure(figsize=(10,6), dpi=80)
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], 
           [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.yticks([-1, 0, +1],
           [r'$-1$', r'$0$', r'$+1$'])
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-")
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('sin/cos')
plt.show()

Moving spines


In [ ]:
ax = plt.gca()
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-")
plt.show()

Adding a Legend


In [ ]:
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-", label="sine")
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.legend(loc='upper left', frameon=False)
plt.show()

In [ ]: