Visualization 1: Matplotlib Basics

Imports

The following imports should be used in all of your notebooks where Matplotlib in used:


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

Basic plotting

For now, we will work with basic x, y plots to show how the Matplotlib plotting API works.


In [5]:
t = np.linspace(0,4*np.pi,100)
plt.plot(t, np.sin(t))
plt.xlabel('Time')
plt.ylabel('Signal')
plt.title('My Plot')


Out[5]:
<matplotlib.text.Text at 0x1128508d0>

Quick series styling

With a third argument you can provide the series color and line/marker style:


In [12]:
plt.plot(t, np.sin(t), 'm-.*')


Out[12]:
[<matplotlib.lines.Line2D at 0x11286fd10>]

Here is a list of the single character color strings:

    b: blue
    g: green
    r: red
    c: cyan
    m: magenta
    y: yellow
    k: black
    w: white

The following will show all of the line and marker styles:


In [9]:
from matplotlib import lines
lines.lineStyles.keys()


Out[9]:
['', ' ', 'None', '--', '-.', '-', ':']

In [11]:
from matplotlib import markers
markers.MarkerStyle.markers.keys()


Out[11]:
[0,
 1,
 2,
 3,
 4,
 'D',
 6,
 7,
 's',
 '|',
 '',
 'None',
 None,
 'x',
 5,
 '_',
 '^',
 ' ',
 'd',
 'h',
 '+',
 '*',
 ',',
 'o',
 '.',
 '1',
 'p',
 '3',
 '2',
 '4',
 'H',
 'v',
 '8',
 '<',
 '>']

To change the plot's viewport, use plt.axis([xmin,xmax,ymin,ymax]):


In [15]:
plt.plot(t, np.sin(t)*np.exp(-0.1*t),'bo')
plt.axis([-1,3,0,1.])


Out[15]:
[-1, 3, 0, 1.0]

Multiple series

You can provide multiple series in a single call to plot:


In [16]:
plt.plot(t, np.sin(t), 'r.', t, np.cos(t), 'g-')


Out[16]:
[<matplotlib.lines.Line2D at 0x112a23c10>,
 <matplotlib.lines.Line2D at 0x112befa10>]

Or you can make multiple calls to plot:


In [17]:
plt.plot(t, np.sin(t))
plt.plot(t, np.cos(t))


Out[17]:
[<matplotlib.lines.Line2D at 0x112c89410>]

Subplots

You can use the subplot function to create a grid of plots in a single figure.


In [20]:
plt.subplot(1,2,1)
plt.plot(t, np.exp(0.1*t))
plt.ylabel('Exponential')
plt.subplot(1,2,2)
plt.plot(t, np.sin(t))
plt.ylabel('Quadratic')
plt.xlabel('x')


Out[20]:
<matplotlib.text.Text at 0x112ec8fd0>

More line styling

All plot commands, including plot, accept keyword arguments that can be used to style the lines in more detail. See Controlling line properties for more details:


In [21]:
plt.plot(t, np.sin(t), marker='o', color='darkblue',
         linestyle='--', alpha=0.3, markersize=10)


Out[21]:
[<matplotlib.lines.Line2D at 0x112c86d50>]

Other plot types

Here are some of the other important plot types we will be using in this course:

  • Scatter plots (plt.scatter)
  • Bar plots (plt.bar and plt.barh)
  • Box plots (plt.boxplot)
  • Histogram (plt.hist)

Resources