Class 4: matplotlib (and a quick Numpy example)

Brief introduction to the matplotlib module.

Preliminary example: Economic growth

A country with GDP in year $t-1$ denoted by $y_{t-1}$ and an annual GDP growth rate of $g$, will have GDP in year $t$ given by the recursive equation:

\begin{align} y_{t} & = (1+g)y_{t-1} \end{align}

Given an initial value of $y_0$, we can find $y_t$ for any given $t$ in one of two ways:

  1. By iterating on the equation
  2. Or by using substitution and deriving: \begin{align} y_t & = (1+g)^t y_0 \end{align}

In this example we'll do both.

Example: Economic growth

A country with GDP in year $t-1$ denoted by $y_{t-1}$ and an annual GDP growth rate of $g$, will have GDP in year $t$ given by the recursive equation:

\begin{align} y_{t} & = (1+g)y_{t-1} \end{align}

Given an initial value of $y_0$, we can find $y_t$ for any given $t$ in one of two ways:

  1. By iterating on the equation
  2. Or by using substitution and deriving: \begin{align} y_t & = (1+g)^t y_0 \end{align}

In this example we'll do both.


In [ ]:
# Define T and g
T = 40
y0 =50 
g = 0

# Compute yT using the direct approach and print


# Initialize a 1-dimensional array called y that has T+1 zeros 


# Set the initial value of y to equal y0



# Use a for loop to update the values of y one at a time



# Print the final value in the array y

matplotlib

matplotlib is a powerful plotting module that is part of Python's standard library. The website for matplotlib is at http://matplotlib.org/. And you can find a bunch of examples at the following two locations: http://matplotlib.org/examples/index.html and http://matplotlib.org/gallery.html.

matplotlib contains a module called pyplot that was written to provide a Matlab-style ploting interface.


In [ ]:
# Import matplotlib.pyplot

Next, we want to make sure that the plots that we create are displayed in this notebook. To achieve this we have to issue a command to be interpretted by Jupyter -- called a magic command. A magic command is preceded by a % character. Magics are not Python and will create errs if used outside of the Jupyter notebook


In [ ]:
# Magic command for the Jupyter Notebook

A quick matplotlib example

Create a plot of the sine function for x values between -6 and 6. Add axis labels and a title.


In [ ]:
# Import numpy as np


# Create an array of x values from -6 to 6


# Create a variable y equal to the sin of x


# Use the plot function to plot the 


# Add a title and axis labels

The plot function

The plot function creates a two-dimensional plot of one variable against another.


In [ ]:
# Use the help function to see the documentation for plot

Example

Create a plot of $f(x) = x^2$ with $x$ between -2 and 2.

  • Set the linewidth to 3 points
  • Set the line transparency (alpha) to 0.6
  • Set axis labels and title
  • Add a grid to the plot

In [ ]:
# Create an array of x values from -6 to 6


# Create a variable y equal to the x squared


# Use the plot function to plot the line


# Add a title and axis labels


# Add grid

Example

Create plots of the functions $f(x) = \log x$ (natural log) and $g(x) = 1/x$ between 0.01 and 5

  • Set the limits for the $x$-axis to (0,5)
  • Set the limits for the $y$-axis to (-2,5)
  • Make the line for $log(x)$ solid blue
  • Make the line for $1/x$ dashd magenta
  • Set the linewidth of each line to 3 points
  • Set the line transparency (alpha) for each line to 0.6
  • Set axis labels and title
  • Add a legend
  • Add a grid to the plot

In [ ]:
# Create an array of x values from -6 to 6


# Create y variables


# Use the plot function to plot the lines


# Add a title and axis labels


# Set axis limits


# legend


# Add grid

Example

Consider the linear regression model: \begin{align} y_i = \beta_0 + \beta_1 x_i + \epsilon_i \end{align} where $x_i$ is the independent variable, $\epsilon_i$ is a random regression error term, $y_i$ is the dependent variable and $\beta_0$ and $\beta_1$ are constants.

Let's simulate the model

  • Set values for $\beta_0$ and $\beta_1$
  • Create an array of $x_i$ values from -5 to 5
  • Create an array of $\epsilon_i$ values from the standard normal distribution equal in length to the array of $x_i$s
  • Create an array of $y_i$s
  • Plot y against x with either a circle ('o'), triangle ('^'), or square ('s') marker and transparency (alpha) to 0.5
  • Add axis lables, a title, and a grid to the plot

In [ ]:
# Set betas


# Create x values


# create epsilon values from the standard normal distribution


# create y


# plot


# Add a title and axis labels


# Set axis limits


# Add grid

Example

Create plots of the functions $f(x) = x$, $g(x) = x^2$, and $h(x) = x^3$ for $x$ between -2 and 2

  • Use the optional string format argument to format the lines:
    • $x$: solid blue line
    • $x^2$: dashed green line
    • $x^3$: dash-dot magenta line
  • Set the linewidth of each line to 3 points
  • Set transparency (alpha) for each line to 0.6
  • Add a legend to lower right with 3 columns
  • Set axis labels and title
  • Add a grid to the plot

In [ ]:
# Create an array of x values from -6 to 6


# Create y variables


# Use the plot function to plot the lines


# Add a title and axis labels


# Add grid


# legend

Figures, axes, and subplots

Often we want to create plots with multiple axes or we want to modify the size and shape of the plot areas. To be able to do these things, we need to explicity create a figure and then create the axes within the figure. The best way to see how this works is by example.

Example: A single plot with double width

The default dimensions of a matplotlib figure are 6 inches by 4 inches. As we saw above, this leaves some whitespace on the right side of the figure. Suppose we want to remove that by making the plot area twice as wide.

Plot the sine function on -6 to 6 using a figure with dimensions 12 inches by 4 inches


In [ ]:
# Create data


# Create a new figure


# Create axis


# Plot


# Add grid

In the previous example the figure() function creates a new figure and add_subplot() puts a new axis on the figure. The command fig.add_subplot(1,1,1) means divide the figure fig into a 1 by 1 grid and assign the first component of that grid to the variable ax1.

Example: Two plots side-by-side

Create a new figure with two axes side-by-side and plot the sine function on -6 to 6 on the left axis and the cosine function on -6 to 6 on the right axis.


In [ ]:
# Create data


# Create a new figure


# Create axis 1 and plot with title


# Create axis 2 and plot with title

Example: Block of four plots

The default dimensions of a matplotlib figure are 6 inches by 4 inches. As we saw above, this leaves some whitespace on the right side of the figure. Suppose we want to remove that by making the plot area twice as wide.

Create a new figure with four axes in a two-by-two grid. Plot the following functions on the interval -2 to 2:

  • $y = x$
  • $y = x^2$
  • $y = x^3$
  • $y = x^4$

Leave the figure size at the default (6in. by 4in.) but run the command plt.tight_layout() to adust the figure's margins after creating your figure, axes, and plots.


In [ ]:
# Create data


# Create a new figure


# Create axis 1 and plot with title


# Create axis 2 and plot with title


# Create axis 3 and plot with title


# Create axis 4 and plot with title


# Adjust margins

Exporting figures to image files

Use the plt.savefig() function to save figures to images.


In [ ]:
# Create data
x = np.arange(-6,6,0.001)
y = np.sin(x)

# Create a new figure, axis, and plot
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(x,y,lw=3,alpha = 0.6)
ax1.grid()

# Save
plt.savefig('fig_econ129_class04_sine.png',dpi=120)

In the previous example, the image is saved as a PNG file with 120 dots per inch. This resolution is high enough to look good even when projected on a large screen. The image format is inferred by the extension on the filename.