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
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]:
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]:
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]:
In [11]:
from matplotlib import markers
markers.MarkerStyle.markers.keys()
Out[11]:
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]:
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]:
Or you can make multiple calls to plot
:
In [17]:
plt.plot(t, np.sin(t))
plt.plot(t, np.cos(t))
Out[17]:
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]:
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]:
Here are some of the other important plot types we will be using in this course:
plt.scatter
)plt.bar
and plt.barh
)plt.boxplot
)plt.hist
)