<jupyter_start><jupyter_text>Class 4: Plotting with MatplotlibMatplotlib 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 plotting interface.<jupyter_code># Import matplotlib.pyplot<jupyter_output><empty_output><jupyter_text>An Introductory ExampleCreate a plot of the sine function for x values between -6 and 6. Add axis labels and a title.<jupyter_code># Import numpy as np


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


# Create a variable y equal to the sine of x


# Use the plot function to plot x on the horizontal axis and y on the vertical axis


# Add a title and axis labels<jupyter_output><empty_output><jupyter_text>Style Sheets and Magic CommandsPlots made using Matplotlib are highly customizable. Users can issue commands to control the limits of the axes, location of axis ticks, labels associated with axis ticks, and the color, thickness, opacity, and style of plotted data points. But as a starting-point, Matplotlib uses a *style sheet* to establish initial plot settings until the user specifies different alternatives. The release of Matplotlib 2.0 included a major change in the default syle and the new default doesn't appeal to me.Next, when we change from the default ploting style, it disrupts how Jupyter formats and displays plots. To fix 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 errors if used in a Python program outside of the Jupyter notebook (i.e., if you are running Python in IDLE or executing a Python script form the command line, make sure to comment out lines with magics).<jupyter_code># Set the Matplotlib style sheet to 'classic'


# Magic command for the Jupyter Notebook to display plots in the notebook


# Use the plot function to plot the sine function


# Add a title and axis labels<jupyter_output><empty_output><jupyter_text>The matplotlib attribute `plt.style.available` stores as a `list` the default sstyle sheets that you can choose from. Here's a gallery of the different sytles compared with each other. Aside from `classic`, other styles that I think look nice include: `bmh`, `ggplot`, and `seaborn`. But try them all out and see what you like!<jupyter_code>#Print the available matplotlib style sheets. PROVIDED
print(plt.style.available)<jupyter_output><empty_output><jupyter_text>The `plot` FunctionThe `plot` function creates a two-dimensional plot of one variable against another.<jupyter_code># Use the help function to see the documentation for plt.plot()<jupyter_output><empty_output><jupyter_text>ExampleCreate a plot of $f(x) = x^2$ with $x$ between -2 and 2.* Set the linewidth to 3 points* Set the line opacity (alpha) to 0.6* Set axis labels and title* Add a grid to the plot<jupyter_code># Create an array of x values from -2 to 2


# Create a variable y equal to x squared


# Use the plot function to plot the line


# Add a title and axis labels


# Add grid<jupyter_output><empty_output><jupyter_text>ExampleCreate plots of the functions $f(x) = \log x$ (natural log) and $g(x) = 1/x$ between 0.01 and 5* Make the line for $log(x)$ solid blue* Make the line for $1/x$ dashed magenta* Set the linewidth of each line to 3 points* Set the line transparency (alpha) for each line to 0.6* Set the limits for the $x$-axis to (0,5)* Set the limits for the $y$-axis to (-2,5)* Set axis labels and title* Add a legend* Add a grid to the plot<jupyter_code># Create an array of x values from 0.01 to 5


# Create y variables


# Use the plot function to plot the lines


# Add a title and axis labels


# Set axis limits


# Make legend


# Add grid<jupyter_output><empty_output><jupyter_text>ExampleConsider 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 $\beta_0=1$ and $\beta_1=-0.5$* 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$ values* Create an array of $y_i$ values* 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<jupyter_code># 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<jupyter_output><empty_output><jupyter_text>ExampleCreate 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.7* Set axis labels and title* Add a legend to lower right with 3 columns* Add a grid to the plot<jupyter_code># Create an array of x values from -2 to 2


# Create y variables


# Use the plot function to plot the lines


# Add a title and axis labels


# Make legend


# Add grid<jupyter_output><empty_output><jupyter_text>Figures, Axes, and SubplotsOften 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 axes within the figure. The best way to see how this works is by example. Example: A Single Plot with Double WidthThe 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 in the Notebook. 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<jupyter_code># Create an array of x values from -6 to 6


# Create y variables


# Create a new figure that is twice as wide as the default


# Create axis within the figure


# Plot


# Add grid<jupyter_output><empty_output><jupyter_text>In the previous example the `fig = plt.figure()` function creates a new figure called `fig` and `fig.add_subplot()` puts a new axis on the figure. The command `ax1 = fig.add_subplot(1,1,1)` means divide the figure `fig` into a 1 by 1 grid (first two arguments) and assigns the first component of that grid to the variable `ax1` (third argument).  Example: Two Plots StackedCreate a new figure with two axes in a column and plot the sine function on -6 to 6 on the top axis and the cosine function on -6 to 6 on the bottom axis.<jupyter_code># Create an array of x values from -6 to 6


# Create y variables


# Create a new figure that is twice as tall as the default


# Create axis 1 and plot with title and axis labels


# Create axis 2 and plot with title and axis labels


# Improve the spacing between the plots<jupyter_output><empty_output><jupyter_text>Example: Block of Four PlotsThe 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$Set the figure size to 12in. by 8in. Run the command `plt.tight_layout()` to adust the figure's margins after creating your figure, axes, and plots.<jupyter_code># Create data for plot


# Create a new figure that is twice as wide and twice as tall as the default


# 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


# Improve the spacing between the plots<jupyter_output><empty_output><jupyter_text>Exporting Figures to Image FilesUse the `plt.savefig()` function to save figures to images.<jupyter_code># Create data to plot sin(x)/x on [-20,20]


# Plot y against x


# Save figure as 'fig_econ126_class04_sine_over_x.png' at 120 DPI resolution<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0665263650181223, 'fraction_numerical': 0.012510230328539694, 'mean_word_length': 4.366373902132999, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '155510', 'license': 'MIT', 'n_tokens_mistral': 2598, 'n_tokens_neox': 2427, 'n_words': 1309, 'path': 'Lecture Notebooks/Econ126_Class_04_blank.ipynb', 'repo_name': 't-hdd/econ126', 'size': '8553'}