\documentclass{article}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphics}
\usepackage{listings}
\usepackage{tcolorbox}
\usepackage{verbatim}

\DeclareMathOperator*{\argmin}{arg\,min}

\marginparwidth 0pt
\oddsidemargin  0pt
\evensidemargin  0pt
\marginparsep 0pt
\topmargin   0pt
\textwidth   6.5in
\textheight  8.5in
\setlength{\parindent}{0em}

\newenvironment{packed_itemize}{
\begin{itemize}
  \setlength{\itemsep}{0pt}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}
}{\end{itemize}}

\newenvironment{packed_enumerate}{
\begin{enumerate}
  \setlength{\itemsep}{1pt}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}
}{\end{enumerate}}

\definecolor{codeback}{RGB}{235,255,255}

\lstset{ %
language=Matlab,                % choose the language of the code
basicstyle=\footnotesize,       % the size of the fonts that are used for the code
numbers=left,                   % where to put the line-numbers
numberstyle=\footnotesize,      % the size of the fonts that are used for the line-numbers
stepnumber=1,                   % the step between two line-numbers. If it is 1 each line will be numbered
numbersep=10pt,                  % how far the line-numbers are from the code
backgroundcolor=\color{codeback},  % choose the background color. You must add \usepackage{color}
showspaces=false,               % show spaces adding particular underscores
showstringspaces=false,         % underline spaces within strings
showtabs=false,                 % show tabs within strings adding particular underscores
frame=single,           % adds a frame around the code
tabsize=2,          % sets default tabsize to 2 spaces
captionpos=b,           % sets the caption-position to bottom
breaklines=true,        % sets automatic line breaking
breakatwhitespace=false,    % sets if automatic breaks should only happen at whitespace
escapeinside={(*@}{@*)}          % if you want to add a comment within your code
}

\begin{document}

\begin{center}
  \Huge{MATLAB Plotting}\\
  \Large{MATH2070: Numerical Methods in Scientific Computing I}
\end{center}
Location: http://people.sc.fsu.edu/$\sim$jburkardt/classes/math2070\_2019/matlab\_plotting/matlab\_plotting.pdf
\vskip 0.1in
\hrule
\vskip 0.1in

\begin{center}
  \includegraphics[scale=1.00]{durer.png}
  \vskip 0.1in
  {\it{How can we illustrate our data and mathematical results?}}
\end{center}
\vskip 0.1in
\begin{tcolorbox}[colback=red!5,title=MATLAB Plots]
{\it{
  Plots represent our data, help us to see patterns
  and problems, and convince our viewers of our results.
}}
\end{tcolorbox}
Plotting allows us to visualize data.  Before we do any analysis, this allows us to explore the data; after an analysis, we use various kinds of plots to analyze and publish our results.  MATLAB has a rich set of plotting commands that we will explore, including
\begin{packed_itemize}
  \item{ {\bf{line plot}}, a sequence of points $(x_i,y_i)$ connected by lines;}
  \item{ {\bf{line plots}}, several graphs on a single plot;}
  \item{ {\bf{scatter plot}}, a set of points $(x_i,y_i)$ indicated by markers;}
  \item{ {\bf{bar plot}}, a set of data $y_i$ displayed as bar heights;}
  \item{ {\bf{histogram plot}}, data to be grouped into bins before bar
         plotting;} 
  \item{ {\bf{contour plot}}, contour lines of a function $f(x,y)$;}
  \item{ {\bf{color contour plot}}, contour colors of a function $f(x,y)$;}
  \item{ {\bf{vector plot}}, a 2D display of vectors (u,v)(x,y), representing
          a gradient field, an ODE direction field, or a flow of some kind.}
  \item{ {\bf{surface plot}}, a 3D plot of the surface $z=f(x,y)$;}
  \item{ {\bf{polygon\_fill}}, polygons filled with color.}
  \item{ {\bf{tree plot}}, representing a branching process;}
  \item{ {\bf{graph plot}}, a set of labeled points $p_i$, and a list of 
          two-way connections $(p_i \leftrightarrow p_j)$.}
  \item{ {\bf{digraph plot}}, a set of labeled points $p_i$, and a list of 
          one-way connections $(p_i \rightarrow p_j)$.}
\end{packed_itemize}

\section{Exercise: Line plot of the BULGARIA data}

The text data file {\it{bulgaria\_data.txt}} records a sequence 
$(y_i, p_i)$, of years and population.  A line plot connects the
data points, suggesting a smooth functional behavior. 
\vskip 0.1in
\begin{packed_itemize}
  \item{load the text data file
\begin{lstlisting}
data = load ( 'bulgaria_data.txt' );
\end{lstlisting}
  }
  \item{plot year versus population (several tries):
  \begin{lstlisting}
plot ( data(:,1), data(:,2) );
plot ( data(:,1), data(:,2), 'r' );
plot ( data(:,1), data(:,2), 'b.', 'markersize', 20 );
plot ( data(:,1), data(:,2), 'go-' );
plot ( data(:,1), data(:,2), 'm-', 'linewidth', 3 );
\end{lstlisting}
  }
  \item{Force y axis to run from 0 to 10,000,000:
\begin{lstlisting}
ylim ( [0.0, 10000000.0 ] )
\end{lstlisting}
  }
  \item{Customize the plot:
\begin{lstlisting}
grid ( 'on' )
xlabel ( '<-- Year -->' )
ylabel ( '<-- Population -->' )
title ( 'Changes in Bulgarian Population' )
title ( 'Changes in Bulgarian Population', 'fontsize', 16 )
\end{lstlisting}
  }
  \item{save a PNG version:
\begin{lstlisting}
print ( '-dpng', 'bulgaria_line_plot.png' );
\end{lstlisting}
  }
\end{packed_itemize}

\section{Exercise: Line plots of the PRICE data}

The file {\it{price\_data.txt}} is a table of average monthly prices for 11 consumer products, between February 2008 and February 2018.  There are 241 records, and each record contains 13 items: the month, the year, and the prices of 11 goods.  Columns 3, 10 and 13 contain the prices of bananas, gas, and milk, respectively.  We want a single plot that shows line plots for all three items together.  There are two ways to do this.
\vskip 0.1in
\begin{packed_itemize}
  \item{load the file, extract data, add month label:
\begin{lstlisting}
  data = load ( 'price_data.txt' );
  bananas = data(:,3);
  gas = data(:,10);
  milk = data(:,13);
  month = 1:241;
\end{lstlisting}
  }
  \item{plot data all at once, or in three steps:
\begin{lstlisting}
  plot ( month, bananas, month, gas, month, milk, 'linewidth', 3 );
  clf ( );
  hold ( 'on' );
  plot ( month, bananas, 'linewidth', 3 );
  plot ( month, gas, 'linewidth', 3 );
  plot ( month, milk, 'linewidth', 3 );
  hold ( 'off' )
\end{lstlisting}
  }
  \item{Finish the plot:
\begin{lstlisting}
  legend ( 'Bananas', 'Gas', 'Milk' );
  grid ( 'on' )
  xlabel ( 'Month Index', 'fontsize', 16 );
  ylabel ( 'Price in Dollars', 'fontsize', 16 );
  title ( 'Prices, Feb 2008-Feb 2018', 'fontsize', 16 );
  print ( '-dpng', 'price_line_plots.png' );
\end{lstlisting}
}
\end{packed_itemize}

\section{Exercise: Scatter plot of the FAITHFUL data}

The file {\it{faithful\_data.txt}} contains 272 
observations of the Old Faithful geyser.  Each line records 2 items:
the eruption length in minutes, and the 
wait in minutes until the next eruption.  It might seem reasonable that 
the two variables are related.  A long 
eruption might mean a long subsequent wait, for 
instance.  Such patterns can be investigated using a 
scatter plot, in which we simply put a mark at each 
point $(x,y)$ for which we have data.

\vskip 0.1in

\begin{packed_itemize}
  \item{load the data:
\begin{lstlisting}
data = load ( 'faithful_data.txt' );
\end{lstlisting}
  }
  \item{Use the plot() command or the scatter() command:
\begin{lstlisting}
  plot ( data(:,1), data(:,1), 'ro', 'markersize', 15 );
  scatter ( data(:,1), data(:,2), 'filled' );
\end{lstlisting}
  }
  \item{Finish the plot:
\begin{lstlisting}
grid ( 'on' )
title ( 'Old Faithful Eruption / Pause Durations' )
xlabel ( '<-- Eruption Duration (minutes)-->' )
ylabel ( '<-- Pause Duration (minutes) -->' )
print ( '-dpng', 'faithful_scatter_plot.png' );
\end{lstlisting}
  }
\end{packed_itemize}

What relationship between eruption time and wait time 
is suggested by the scatter plot of the data?

\section{Exercise: Bar plot of the SCHOOLYEAR data}

Both line and scatter plots assume each data item has 
the form $(x,y)$.  Sometimes, however, instead of $x$ 
data, we have some kind of label.  Thus, we might have a 
list of car models and their prices.  A bar plot allows 
us to represent the data as bars, identified by their 
data labels, with heights proportional to the data 
values.
\vskip 0.1in
MATLAB has some trouble reading data files that contain 
a mixture of text and numeric data, so instead, we will 
get our data from a MATLAB function.
\vskip 0.1in

\begin{packed_itemize}
  \item{Get country name and schoolyear length from function {\it{schoolyear\_data.m}}:
\begin{lstlisting}
  [ country, days ] = schoolyear_data ( );
\end{lstlisting}
  }
\item{Make a horizontal bar plot of days, and use country names as labels:
\begin{lstlisting}
  barh ( days );
  set ( gca, 'yticklabel', country );
\end{lstlisting}
  }
\item{Finish the plot:
\begin{lstlisting}
  grid ( 'on' );
  xlabel ( '<-- School Year in Days -->', 'FontSize', 16 );
  title ( 'International Variation in School Year', 'FontSize', 24 );
  print ( '-dpng', 'schoolyear_bar_plot.png' );
\end{lstlisting}
  }
\end{packed_itemize}

\section{Exercise: Histogram of the SNOWFALL data}

Suppose we want to display a large set of observations of some numerical quantity, $(x_1,x_2,...,x_n)$.  If the data has some slowly varying trend, a line plot might be suitable.  If the data is not too numerous, a bar plot might work.  But if the data is numerous and somewhat chaotic, we are better off with a {\it{histogram}}, which simplifies the data by grouping it into a small number of bins.  A histogram then shows how many data items fall into each range.

\vskip 0.1in
\begin{packed_itemize}
  \item{load the file {\it{snowfall\_data.txt}} and extract column 10:
\begin{lstlisting}
data = load ( 'snowfall_data.txt');
inches = data(:,10);
\end{lstlisting}
  }
  \item{Create a bar plot (bad idea), then switch to histogram, then specify number of bins: 
\begin{lstlisting}
bar ( inches );
histogram ( inches );
histogram ( inches, 25 );
\end{lstlisting}
  }
  \item{Finish the plot:
\begin{lstlisting}
grid ( 'on' );
xlabel ( '<-- Total Yearly Snowfall in Inches -->' );
ylabel ( '<-- Frequency -->' );
title ( 'Yearly Snowfall in Michigan' );
print ( '-dpng', 'snowfall_histogram.png' );
\end{lstlisting}
  }
\end{packed_itemize}

What features of the data does the histogram allow you 
to see right away?

\section{Exercise: Contour plot of the VOLCANO data}

We may have a collection of measurements of temperature, or elevation, or pollution levels, sampled at regular points on a grid.  One way to visualize such data is to use a contour plot.  Contours can be indicated by a sequence of curves, each of which connects points with the same value of the measurement; a more vivid image can be done using colors.
\vskip 0.1in
\begin{packed_itemize}
  \item{access an $82 \times 61$ array {\tt{z}} from data file {\it{volcano\_data.txt}}:
\begin{lstlisting}
z = load ( 'volcano_data.txt');
\end{lstlisting}
  }
  \item{Make a line contour plot:
\begin{lstlisting}
contour ( z, 'linewidth', 3 );
\end{lstlisting}
  }
  \item{Make a color contour plot with colorbar:
\begin{lstlisting}
contourf ( z );
colorbar ( );
\end{lstlisting}
  }
\item{Make a surface plot with colorbar:
\begin{lstlisting}
  surf ( z, 'edgecolor', 'none' );
  colorbar ( );
  xlabel ( '<-- X -->' );
  ylabel ( '<-- Y -->' );
  zlabel ( '<-- Z -->' );
  title ( 'Surface plot of volcano height' );
  print ( '-dpng', 'volcano_surface.png' );
\end{lstlisting}
  }
\end{packed_itemize}

\section{Exercise: Vector plot of the HEX2() function}

Recall the {\it{hex2()}} function that we tried to minimize in a
previous lab:
\begin{displaymath}
  f(x,y) = 2 x^2 - 1.05 x^4 + x^6 / 6 + x y + y^2
\end{displaymath}
It would be interesting to see a plot displaying both the contour lines
of this function, and the field of negative gradient vectors that 
point towards local minimizers.
\vskip 0.1in

\begin{packed_itemize}
  \item{create vectors $x$ and $y$, then tables $X$ and $Y$.  Define
  $Z(X,Y)$ by calling hex2():
  \begin{lstlisting}
x = linspace ( -2, +2, 31 );
y = linspace ( -2, +2, 31 );
[X,Y] = meshgrid ( x, y );
Z = hex2 ( X, Y );    % I modified hex2() to take two separate inputs.
\end{lstlisting}
  }
  \item{Estimate the gradient using finite differences:
  \begin{lstlisting}
h = 0.01;
[ dZdX, dZdY ] = gradient ( Z, h );
\end{lstlisting}
  }
  
  \item{Make one plot with both contours and vectors:
\begin{lstlisting}
hold ( 'on' );
contour ( X, Y, Z, 25 );
quiver ( X, Y, -dZdX, -dZdY, 2.0 );
hold ( 'off' )
\end{lstlisting}
  }
\end{packed_itemize}
We could also have written a function to evaluate the gradient exactly,
instead of calling MATLAB's {\tt{gradient()}} function.

\section{Exercise: Surface plot of the MEXICAN\_HAT function}

A contour plot can also be useful to examine the 
behavior of a function $z=f(x,y)$; even better is a 3D 
surface plot.  In this case, we have to generate the $(x,y)$ 
grid values, and set up a way to evaluate the 
function.

\vskip 0.1in

\begin{packed_itemize}
  \item{create vectors $x$ and $y$, then tables $X$ and $Y$.  Define
  $Z(X,Y)$ using an auxilliary variable $R$:
  \begin{lstlisting}
x = linspace ( -8, 8, 33 );
y = linspace ( -8, 8, 33 );
[X,Y] = meshgrid ( x, y );
R = sqrt ( X.^2 + Y.^2 + eps );
Z = sin ( R ) ./ R;
\end{lstlisting}
  }
  \item{Compare contour, color contour, and surface plots:
\begin{lstlisting}
contour ( X, Y, Z );
contourf ( X, Y, Z );
surf ( X, Y, Z );
\end{lstlisting}
  }
\end{packed_itemize}

\section{Exercise: polygon fill plot of MARIO}

The MATLAB {\tt{fill()}} command can be used to create a plot made up
of one or more polygons, each filled with a specific color.
\vskip 0.1in
The form of the command is {\tt{fill(X,Y,C)}},
where {\tt{X}} and {\tt{Y}} are the coordinates of a polygon's vertices,
and {\tt{C}} is a 3-component RGB color specification, that is, real numbers
between 0 and 1.
To get an idea of how this works, type
\begin{lstlisting}
hold ( 'on' )
fill ( [0,1,0], [0,0,1], [1,0,0] )
fill ( [0.5, 1.0, 1.0, 0.5 ], [0.5, 0.5, 1.0, 1.0 ], [0,0,1] )
axis ( 'square' )  % (otherwise, a square looks like a rectangle)
hold ( 'off' )
\end{lstlisting}
This command can be used to make beautiful contour color plots,
diagrams of meshes, tilings, and other images.  However, to make
an interesting plot often requires entering a lot of data.
\vskip 0.1in
To see the kind of plots this command can create,
download the file {\it{mario.m}} and run it!
 
\section{Exercise: Tree plot of the GENEALOGY data}

A tree plot is way to illustrate a process which 
involves branching or dependence.  A tree plot can
illustrate all the paths that start at the initial point 
and branch one way or another at decision points.

The locations on a tree are called {\it{nodes}}, and the 
node representing the initial state is called the 
{\it{root node}}.  If we assign each node an identifying 
index, then the structure of the tree can be described 
if each node identifies its ``parent node'', which connects it back to the root node.

\vskip 0.1in
\begin{packed_enumerate}
  \item{create a tree description and display the tree:
  \begin{lstlisting}
nodes = [ 0, 1, 2, 2, 4, 4, 4, 1, 8, 8, 10, 10 ];
treeplot ( nodes );
\end{lstlisting}
  }
  \item{Create labels for the nodes:
\begin{lstlisting}
labels = { ...
  'Adam',
  'Bert',
  'Carl',
  'Dale',
  'Eddy',
  'Fred',
  'Gina',
  'Hank',
  'Inez',
  'Jane',
  'Kurt',
  'Leah' };
\end{lstlisting}
  }
  \item{Find out where the nodes are, and attach the labels to the nodes:
\begin{lstlisting}
[ x, y ] = treelayout ( nodes );
for i = 1 : length ( x )
  text ( x(i) + 0.1, y(i), labels{i} );
end
\end{lstlisting}
  }
\end{packed_enumerate}

\section{Exercise: Graph plot of the NETWORK data}

Mathematically, a graph is a set of {\it{nodes}}, some of which are connected by {\it{edges}}.  The edges usually represent two-way connections; one-way connections arise in ``directed graphs''.

The MATLAB function {\it{graph()}} can define a graph $G$ using two lists of equal length, containing the starting node $s$ and terminal node $t$ of each
edge.  

For your exercise, consider the following network:
\begin{center}
%\begin{figure}
  \scalebox{0.75}
  {\includegraphics{network_graph.png}}\\
  A plot of the network data.
%\end{figure}
\end{center}
\vskip 0.1in
\begin{packed_enumerate}
  \item{use the picture above to fill in the missing data in these
  MATLAB commands that define the edges:
  \begin{lstlisting}
s = [ 1, 1, 2, ..., 10 ];
t = [ 2, 3, 4, ..., 11 ];
\end{lstlisting}
  }
  \item{Use the edges to create a graph called $G$, and plot it:
  \begin{lstlisting}
G = graph ( s, t );
plot ( G );
title ( 'A Network graph' )
\end{lstlisting}
  }
\end{packed_enumerate}

\section{Exercise: Directed graph plot of the WEB data}

A directed graph displays nodes connected by one-way edges.  There may be a value associated with each edge, representing a weight, length or probability of access.  A good display should include that information.

For your exercise, consider the following network, and assume that nodes 
1 through 6 are labeled Alpha, Beta, Gamma, Delta, Epsilon and Zeta, respectively.
\begin{center}
%\begin{figure}
  \scalebox{0.75}
  {\includegraphics{web_digraph.png}}\\
  A plot of the web data.
%\end{figure}
\end{center}
\vskip 0.1in
\begin{packed_enumerate}
  \item{use the picture above to describe the graph of the network 
  by filling in the $s$ and $t$ vectors:
  \begin{lstlisting}
s = [ 1, 1, 2, ..., 6 ];
t = [ 5, 6, 1, ..., 4 ];
\end{lstlisting}
  }
  \item{Define the digraph and label each node and edge:
\begin{lstlisting}
G = digraph ( s, t, nodenames );
node_labels = { 'Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zeta' };
edge_labels = { 'AE', 'AZ', 'BA', 'BG', 'BD', 'GD', 'GE', 'DE', 'EA', 'EZ', 'ZA' };
\end{lstlisting}
  }
  \item{Plot the graph
\begin{lstlisting}
> plot ( G, ...
  'Layout', 'circle', ...
  'EdgeLabel', edge_labels, ...
  'NodeLabel', node_labels, ...
  'ArrowSize', 15 );
\end{lstlisting}
  }
\end{packed_enumerate}

\section { No Computing Assignment for this Lab!}

\end{document}

