Imports

Import matplotlib, the matplotlib.pylab and numpy, as they are needed in almost any case.


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

Simple plots

2D plots with X and Y axis data, no special formatting


In [4]:
plt.plot([1,2,6,4,7,9])
plt.ylabel('"random" numbers')
plt.xlabel('the X-axis is undefined and defaults to 0-5')
plt.show()



In [6]:
plt.plot([1,2,3,5], [1,4,9,16])
plt.ylabel('some numbers')
plt.xlabel('now the X-axis goes from 1 to 4')
plt.show()


Coloring the plots

The color formats are either RGB codes in the "#RRBBGG" or [RR, GG, BB] formats or one of the following basic built-in colors:

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

In [16]:
plt.plot([1,2,3,4,5,6], [1,4,9,16, 20, 21], 'go')
plt.ylabel('some numbers')
plt.xlabel('X')
plt.xlim(0,6*1.2)
plt.show()


Adding many data series to one plot with different colors


In [56]:
t = np.arange(0., 1., 0.04)
plt.plot(
    t, t, 'r--', 
    t, t**2, 'bs', 
    t, t**3, 'g^', 
    t, t**4, 'co'
)

plt.plot(t, t**3.5, 'k-')

plt.title(u'This plot also features many data series in one plot')
plt.xlabel('X')
plt.ylabel('different data series')
plt.show()


Defining colors using RGB codes


In [58]:
plt.plot([1,2,3,4,5,6], [1,4,9,16, 20, 21], linestyle='-', linewidth=2.0, color='#00aadd')
plt.plot([1,2,3,4,5,6], [2,5,10,17, 21, 22], linestyle='-', linewidth=2.0, color='#ff6700')
plt.ylabel('some numbers')
plt.xlabel('X')
plt.title(u'Custom color using RGB code')
plt.xlim(0,7)
plt.show()


Axes


In [30]:
x=[1,2,3,4,5,6]
plt.plot(x, [1,4,9,16, 20.3, 21], 'go')
plt.ylabel('some numbers')
plt.xlabel('X')
plt.axis([0, 8, 0, 33])
plt.grid(True)
plt.show()



In [34]:
x=[1,2,3,4,5,6]
labels=['First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth']

plt.plot(x, [1,4,9,16, 20, 21], 'go')
plt.ylabel('some numbers')
plt.xlabel('X')
plt.xticks(x, labels, rotation='vertical')
plt.axis([0, 7, 0, 33])
axes = plt.gca()
axes.xaxis.set_ticks_position('bottom')
axes.minorticks_on()
axes.yaxis.set_ticks_position('both')
plt.show()


Resizing a plot


In [36]:
x=[1,2,3,4,5,6]
plt.figure(figsize=(3,3))
plt.plot(x, [1,4,9,16, 20, 21], 'ko')
plt.ylabel('some numbers')
plt.xlabel('X')
plt.axis([0, 8, 0, 33])
plt.show()

plt.figure(figsize=(5,2))
plt.plot(x, [1,4,9,16, 20, 21], 'ko')
plt.ylabel('some numbers')
plt.xlabel('X')
plt.axis([0, 8, 0, 33])
plt.show()


Annotations

We can use LaTeX in the plots for any texts, eg. labels, annotations, etc.


In [37]:
plt.plot([1,2,3,3.1415,4,5,6], [1,4,9,3.1415**2.0,16, 20, 21], 'ro')
plt.ylabel('some numbers')
plt.xlabel('X')
plt.text(0.5, 25, r'This plot contains $\pi^2$ at $\pi$.', fontsize=20, color='#8900b6')
plt.annotate(r'This is $\pi^2$ at $\pi$!', xy=(3.1415+0.05, 3.1415**2.0-0.1), xytext=(3.5, 3),
            arrowprops=dict(facecolor='black', shrink=0.05), fontsize=20)
plt.axis([0, 8, 0, 33])
plt.grid(True)
plt.show()


Histrograms


In [59]:
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(1000)

n, bins, patches = plt.hist(x, 20, facecolor='y', alpha=0.4)

plt.xlabel('X')
plt.ylabel('Number of data points in bins')
plt.title(r'Histogram example, $\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 200])
plt.grid(True)
plt.show()


Subplots


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

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

plt.figure(figsize=(6,6))

plt.subplot(2, 2, 1)
plt.title('A plot of 2 subplots')
plt.plot(x2, y2, 'g-')
plt.ylabel('Oscillation')

plt.subplot(2, 2, 2)
plt.plot(x1, y1, 'm--')
plt.ylabel('Damped oscillation')
plt.xlabel('time (s)')

plt.subplot(2, 2, 3)
plt.title('A plot of 2 subplots')
plt.plot(x2, y2, 'g-')
plt.ylabel('Oscillation')

plt.subplot(2, 2, 4)
plt.plot(x1, y1, 'm--')
plt.ylabel('Damped oscillation')
plt.xlabel('time (s)')

plt.tight_layout(pad=3.0)
plt.savefig("figure.pdf")
plt.savefig("figure.png")
plt.savefig("figure.svg")
plt.show()


Images


In [50]:
import matplotlib.image as mpimg
img=mpimg.imread('jupiter.jpg')
imgplot = plt.imshow(img)
plt.title('Jupiter')
plt.show()



In [51]:
import matplotlib.patches as patches
fig, ax = plt.subplots()
im = ax.imshow(img)
patch = patches.Circle((565, 545), radius=530, transform=ax.transData)
im.set_clip_path(patch)

plt.axis('off')
plt.title('Cropped Jupiter')
plt.show()



In [54]:
lum_img = img[:,:,0]
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('winter') # or hot or winter or summer or etc.
plt.colorbar()
plt.title('False red channel color Jupiter')
plt.show()