3.1 Making Quick Exploratory plots
Example 1 : Simple Start
from matplotlib import pyplot as plt
# Some data for plotting
= [0, 1, 2, 3, 4, 5]
x = [0, 2, 4, 6, 8, 10]
y1 = [2*y for y in y1]
y2
# Lets start plotting
plt.plot(x, y1,='r', linestyle='dashed', label='Y1 values')
color
plt.scatter(x, y2,='b', label='Y2 values')
color
'x-values')
plt.xlabel('y-values')
plt.ylabel(
=.5)
plt.grid(alpha
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
= [0, 1, 2, 3, 4, 5]
x = [0, 2, 4, 6, 8, 10]
y1 = [2*y for y in y1]
y2 = [.125*y for y in y2]
err
# Lets start plotting
=(10, 5)) # In inches
plt.figure(figsize
plt.plot(x, y1,='r', linestyle='dashed', label='Y1 values')
color=err,
plt.errorbar(x, y2, yerr='b',fmt='o',label='Y2 values')
color# <ErrorbarContainer object of 3 artists>
'x-values')
plt.xlabel('y-values')
plt.ylabel(
=.5)
plt.grid(alpha='upper left')
plt.legend(loc
'example_fig.png', dpi=150)
plt.savefig( plt.show()
Example 3 : Two Y Axes
from matplotlib import pyplot as plt
# Some data for plotting
= [0, 1, 2, 3, 4, 5]
x = [0, 2, 4, 6, 8, 10]
y1 = [y**2 for y in y1]
y2
# Lets start plotting
# ---------------------------------------------------------------------------- #
plt.plot(x, y1,='r', linestyle='dashed', label='Y1 values')
color=.5)
plt.grid(alpha=(.025,.9)) # As fraction of the size of the plot
plt.legend(loc'y')
plt.ylabel('x-values')
plt.xlabel(
# ---------------------------------------------------------------------------- #
# Add another y-axis that shares the x-axis
plt.twinx()
plt.plot(x, y2,='b', linestyle='dashed', label='Y2 values')
color
'y$^2$') # Use LaTeX for the superscript
plt.ylabel(=.5)
plt.grid(alpha=(.025,.8))
plt.legend(loc# ---------------------------------------------------------------------------- #
'example_fig.png', dpi=150)
plt.savefig( plt.show()
Example 4 : Fill Between
import numpy as np
from matplotlib import pyplot as plt
= np.linspace(-np.pi, np.pi, num=100, endpoint=True)
x = np.cos(x)
cos_x = np.sin(x)
sin_x
='sin x')
plt.plot(x, sin_x, label='cos x')
plt.plot(x, cos_x, label
=cos_x > sin_x,
plt.fill_between(x, cos_x, sin_x, where='orange', alpha=.125, label='cos x > sin x')
color
=cos_x < sin_x,
plt.fill_between(x, cos_x, sin_x, where='b', alpha=.075, label='cos x < sin x')
color
plt.legend()='x', alpha=.5)
plt.grid(axis plt.show()