3.1 Making Quick Exploratory plots

Example 1 : Simple Start

from matplotlib import pyplot as plt

# Some data for plotting
x = [0, 1, 2, 3, 4, 5]
y1 = [0, 2, 4, 6, 8, 10]
y2 = [2*y for y in y1]

# Lets start plotting

plt.plot(x, y1,
        color='r', linestyle='dashed', label='Y1 values')
plt.scatter(x, y2,
        color='b', label='Y2 values')

plt.xlabel('x-values')
plt.ylabel('y-values')

plt.grid(alpha=.5)
plt.legend()

plt.show()

Example 2 : Error Bars

Lets:

  • Set a figure size (figsize=(10,5))
  • Add errorbars (errorbar())
  • Specify the quality of the saved figure (dpi=150).
from matplotlib import pyplot as plt

# Some data for plotting
x = [0, 1, 2, 3, 4, 5]
y1 = [0, 2, 4, 6, 8, 10]
y2 = [2*y for y in y1]
err = [.125*y for y in y2]

# Lets start plotting

plt.figure(figsize=(10, 5))        # In inches

plt.plot(x, y1,
         color='r', linestyle='dashed', label='Y1 values')
plt.errorbar(x, y2, yerr=err,
             color='b',fmt='o',label='Y2 values')
# <ErrorbarContainer object of 3 artists>
plt.xlabel('x-values')
plt.ylabel('y-values')

plt.grid(alpha=.5)
plt.legend(loc='upper left')

plt.savefig('example_fig.png', dpi=150)
plt.show()

Example 3 : Two Y Axes

from matplotlib import pyplot as plt

# Some data for plotting
x = [0, 1, 2, 3, 4, 5]
y1 = [0, 2, 4, 6, 8, 10]
y2 = [y**2 for y in y1]

# Lets start plotting

# ---------------------------------------------------------------------------- #
plt.plot(x, y1,
         color='r', linestyle='dashed', label='Y1 values')
plt.grid(alpha=.5)
plt.legend(loc=(.025,.9))          # As fraction of the size of the plot
plt.ylabel('y')
plt.xlabel('x-values')

# ---------------------------------------------------------------------------- #
plt.twinx()                        # Add another y-axis that shares the x-axis
plt.plot(x, y2,
         color='b', linestyle='dashed', label='Y2 values')

plt.ylabel('y$^2$')                # Use LaTeX for the superscript
plt.grid(alpha=.5)
plt.legend(loc=(.025,.8))
 # ---------------------------------------------------------------------------- #

plt.savefig('example_fig.png', dpi=150)
plt.show()

Example 4 : Fill Between

import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(-np.pi, np.pi, num=100, endpoint=True)
cos_x = np.cos(x)
sin_x = np.sin(x)

plt.plot(x, sin_x, label='sin x')
plt.plot(x, cos_x, label='cos x')

plt.fill_between(x, cos_x, sin_x, where=cos_x > sin_x,
                 color='orange', alpha=.125, label='cos x > sin x')

plt.fill_between(x, cos_x, sin_x, where=cos_x < sin_x,
                 color='b', alpha=.075, label='cos x < sin x')

plt.legend()
plt.grid(axis='x', alpha=.5)
plt.show()