Matplotlib

Using matplotlib in Jupyter notebook


In [1]:
import matplotlib.pyplot as plt
%matplotlib inline

In [2]:
import numpy as np

Line Plots

plt.plot Plot lines and/or markers:

  • plot(x, y)
    • plot x and y using default line style and color
  • plot(x, y, 'bo')
    • plot x and y using blue circle markers
  • plot(y)
    • plot y using x as index array 0..N-1
  • plot(y, 'r+')
    • Similar, but with red plusses

run

%pdoc plt.plot

for more details


In [3]:
x = np.arange(-np.pi,np.pi,0.01) # Create an array of x values from -pi to pi with 0.01 interval
y = np.sin(x) # Apply sin function on all x
plt.plot(x,y)


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

In [4]:
plt.plot(y)


Out[4]:
[<matplotlib.lines.Line2D at 0x7f5a0b8f3be0>]

Scatter Plots

plt.plot can also plot markers.


In [5]:
x = np.arange(0,10,1)  # x = 1,2,3,4,5...
y = x*x # Squared x
plt.plot(x,y,'bo') # plot x and y using blue circle markers


Out[5]:
[<matplotlib.lines.Line2D at 0x7f5a0b86a2b0>]

In [6]:
plt.plot(x,y,'r+') # plot x and y using red plusses


Out[6]:
[<matplotlib.lines.Line2D at 0x7f5a0b7c8a90>]

Plot properties

Add x-axis and y-axis


In [7]:
x = np.arange(-np.pi,np.pi,0.001)
plt.plot(x,np.sin(x))
plt.title('y = sin(x)')    # title
plt.xlabel('x (radians)')  # x-axis label
plt.ylabel('y')            # y-axis label


Out[7]:
Text(0, 0.5, 'y')

In [8]:
# To plot the axis label in LaTex, we can run
from matplotlib import rc
## For sans-serif font:
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)

In [9]:
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})

In [10]:
plt.plot(x,np.sin(x))
plt.title(r'T = sin($\theta$)')    # title, the `r` in front of the string means raw string
plt.xlabel(r'$\theta$ (radians)')  # x-axis label, LaTex synatx should be encoded with $$
plt.ylabel('T')            # y-axis label


Out[10]:
Text(0, 0.5, 'T')
/home/yanyan/anaconda3/lib/python3.7/site-packages/matplotlib/font_manager.py:1241: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
  (prop.get_family(), self.defaultFamily[fontext]))
/home/yanyan/anaconda3/lib/python3.7/site-packages/matplotlib/font_manager.py:1241: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
  (prop.get_family(), self.defaultFamily[fontext]))

Multiple plots


In [11]:
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, '.-')
plt.title('Plot 2 graph at the same time')
plt.ylabel('Amplitude (Damped)')

plt.subplot(2, 1, 2)
plt.plot(x2, y2, '.-')
plt.xlabel('time (s)')
plt.ylabel('Amplitude (Undamped)')


Out[11]:
Text(0, 0.5, 'Amplitude (Undamped)')

Save figure


In [12]:
plt.plot(x,np.sin(x))
plt.savefig('plot.pdf')
plt.savefig('plot.png')



In [13]:
# To load image into this Jupyter notebook
from IPython.display import Image
Image("plot.png")


Out[13]: