%\VignetteIndexEntry{Getting Started with Lattice}
%\VignettePackage{HTSandGeneCentricLabs}
\documentclass{article}

\usepackage{BioconductorVignette}
%\include{labheader}

\begin{document}

\SweaveOpts{keep.source=TRUE,width=9,height=8,eps=FALSE,include=FALSE}

\title{Getting Started with Lattice}
\maketitle

\tableofcontents
\listoffigures

<<setup, echo=FALSE>>=
options(width=60)
olocale = Sys.setlocale(locale="C")
vers <- R.Version()
vers <- paste(vers$major, vers$minor, sep = ".")
@


\section{Introduction}

The \Rpackage{lattice} package implements the Trellis graphics system and
provides high-level functions for visualization of multivariate data.
This lab covers some of the basics of the lattice package.

Although the \Rpackage{lattice} package is included in \R{}, you must
explicitly load the package to make use of the functions it provides:

<<loadLattice, echo=TRUE, results=hide>>=
library("lattice")
@

Lattice provides several plotting functions, some of the commonly used ones are
listed below.

\begin{table}[h!]
  \begin{center}
\begin{tabular}{|l|l|}
\hline
\multicolumn{2}{|c|}{Lattice functions} \\
\hline
xyplot() & Scatter plot \\
dotplot() & Cleveland dot plot \\
bwplot() & Box and whisker plot \\
histogram() & Histogram \\
densityplot() & Kernel density plot \\
qq() & Two sample quantile plot \\
\hline
\end{tabular}
\end{center}
 \caption{Commonly used high-level lattice functions}
\end{table}


\section{Basic ideas}

A typical call to the lattice function \Rfunction{xyplot} is shown below.
<<xyplotFormula, eval=FALSE>>=
xyplot(y ~ x | c, data, groups = g)
@

The arguments to a lattice function can be summarized in terms of
\begin{enumerate}
  \item lattice function: A lattice plotting function such as
          \Rfunction{xyplot}, Rfunction{dotplot} etc.
  \item formula: The first argument to a lattice method is a formula. The
	formula for our example is \code{y} \verb+~+ \code{x | c}. If the
        lattice  method takes only a single vector as input, the formula can
        be expressed as  \verb+~+ \code{ x | c}.
    \begin{itemize}
      \item primary variables: Variables y (Y axis of the plot) and x (X
            axis of the plot) that defines the lattice display separated by the
            \verb+~+ character. 
      \item conditioning variable: Variable c in the example separated from
            the primary variables by the character \code{|}. The conditioning
            variable divides the plot into separate panels.
    \end{itemize}
  \item grouping variable: The variable g in the example. The grouping
          variable segregates data into subgroups within each panel.
  \item data: A \Rclass{data.frame} with column names corresponding to the
	variables y, x, c and g. 
\end{enumerate}

Lattice functions do not, in fact, generate a visual display. They return an
object of class \Rclass{trellis} which will generate the desired display when
printed using the \Rfunction{print} function.

\section{Scatter plot (\Rfunction{xyplot})}

We will use the Indometh data that contains plasma concentrations of
the drug indomethicin for six subjects over a period of eight hours to
illustrate a few aspects of \Rpackage{lattice}.  First, we will use
\Rfunction{xyplot} to produce a scatterplot of concentration of the
drug over time. (Figure~\ref{basicXYPlotPrint})

<<loadIndo>>=
data(Indometh)
df <- Indometh
head(df)
@

<<basicXYPlot, echo = FALSE>>=
myplot <- xyplot(conc ~ time, data = df,
                 main = "Pharmacokinetics of Indomethicin",
                 ylab = "Concentration (mcg/ml)",
                 xlab = "Time (hours)")
@

<<basicXYPlotPrint, fig=TRUE, include=FALSE, prefix=FALSE, width=4, height=4, echo=FALSE>>= 
print(myplot)
@

\begin{Ext}\label{ex:concTime}

Reproduce the concentration vs time plot from
Figure~\ref{basicXYPlotPrint} by following the steps described below.
\begin{enumerate}
  \item Create a scatter plot using \Rfunction{xyplot}.  Use the formula
    \code{ conc} \verb+~+ \code{time} with \Robject{df} as the data argument.
  \item Change the X--axis label to 'Time (hours)' by adding an
    \Robject{xlab} argument to the \Rfunction{xyplot} call.
  \item Similarly, change the Y--axis label to 'Concentration
    (mcg/ml)' using \Robject{ylab}.
  \item Finally, change the title of the plot by adding a \Robject{main}
    argument.
\end{enumerate}
\end{Ext}

\begin{Solution}
<<labelPlot>>=
myplot <- xyplot(conc ~ time, data = df,
                 xlab = "Time (hours)",
                 ylab = "Concentration (mcg/ml)",
                 main = "Pharmacokinetics of Indomethicin")
@
\end{Solution}

A scatter plot with the concentration profile for each patient appearing in a
separate panel can be seen in Figure~\ref{xyPlotCondPrint}. This plot was
produced by making use of \Robject{Subject} as the conditioning variable.

<<xyPlotCond, echo=FALSE>>=
myplot <- xyplot(conc ~ time | factor(Subject, levels = 1:6),
                 data = df,
                 main = "Pharmacokinetics of Indomethicin",
                 ylab = "Concentration (mcg/ml)",
                 xlab = "Time (hours)")
@

<<xyPlotCondPrint,fig=TRUE,include=FALSE,prefix=FALSE,width=4,height=4,echo=FALSE>>=
print(myplot)
@

\begin{Ext}
	\begin{enumerate}
		\item Create a scatter plot by adding the conditioning variable
		  \Robject{Subject} to the formula from
                  Exercise~\ref{ex:concTime}. 
		
		\item Modify the conditioning variable in the formula to
		  \Robject{factor(Subject, levels = 1:6)} and observe the
                  difference in the order of plots.		
	\end{enumerate}
\end{Ext}

\begin{Solution}

<<xyPlotCondOrdered>>=
myplot <- xyplot(conc ~ time | factor(Subject, levels = 1:6),
			data = df, main = "Pharmacokinetics of Indomethicin",
			ylab = "Concentration (mcg/ml)",
			xlab = "Time (hours)")
@

\end{Solution}

A scatter plot produced by superimposing the concentration profiles from
all the subjects to a single panel can be seen in
Figure~\ref{xyPlotGroupingPrint}. The figure makes use of lines instead of
points and also has a legend to help distinguish the concentration profiles of
different subjects.

<<xyPlotGrouping, echo=FALSE>>=
myplot <- xyplot(conc ~ time, data = df, groups = Subject, type='l',
                 auto.key = list(space = "right"),
				 main = "Pharmacokinetics of Indomethicin",
				 ylab = "Concentration (mcg/ml)",
				 xlab = "Time (hours)")
@

<<xyPlotGroupingPrint,fig=TRUE,include=FALSE,prefix=FALSE,width=4,height=4,echo=FALSE>>=
print(myplot)
@


\begin{Ext}
	\begin{enumerate}
		\item Create a single scatter plot of the superimposed
                  concentrations by making use of forumula \code{ conc}
                  \verb+~+ \code{time} and  the additional argument
                  \Robject{groups = Subject} to the \Rfunction{xyplot}
                  function.  
		\item Add an additional argument \Robject{type='l'} to the
                  function and observe what effect it has on the plot.
		\item Add an additional arugment \Robject{auto.key =
                  list(space = "right")} to the \Rfunction{xyplot} to add a
                  legend to the right of the plot.
	\end{enumerate}
\end{Ext}

\begin{Solution}
<<xyPlotLegend>>=
myplot <- xyplot(conc ~ time, data = df, groups = Subject, type='l',
                 auto.key = list(space = "right"),
				 main = "Pharmacokinetics of Indomethicin",
				 ylab = "Concentration (mcg/ml)",
				 xlab = "Time (hours)")
@

\end{Solution}

\section{Box and whisker plots (\Rfunction{bwplot})}

We are interested in finding out differences in the plasma concentration of
Indomethicin amongst the six subjects. A box and whisker plot of the
concentration of Indomethicin produced using the \Rfunction{bwplot} method can
be observed in Figure~\ref{bwPlotPrint}

<<bwPlot, echo=FALSE>>=

myplot <- bwplot(~ conc | Subject, data = df, layout = c(1,6),
			main = "Concentration of Indomethicin",
			xlab = "Concentration (mcg/ml)"
				 )
@

<<bwPlotPrint,fig=TRUE,include=FALSE,prefix=FALSE,width=4,height=4,echo=FALSE>>=

print(myplot)
@


\begin{Ext}
	\begin{enumerate}
	  \item Create a boxplot using the formula \verb+~+ \code{conc} and
		the lattice function \Rfunction{bwplot}.
	  \item Update the formula to \verb+~+ \code{conc | Subject} in order
                to add a conditioning variable to the boxplot. 
	  \item Add an additional argument \Robject{layout=c(6,1)} to the
		\Rfunction{bwplot} and observe its effect on the plot.
	\end{enumerate}
\end{Ext}

\begin{Solution}
<<bwPlotStacked>>=
myplot <- bwplot(~ conc | Subject, data = df, layout = c(1,6),
			main = "Concentration of Indomethicin",
			xlab = "Concentration (mcg/ml)"
				 )
@
\end{Solution}

\section{Further Reading}

\begin{itemize}
  \item The \Rpackage{lattice} package includes many detailed help
    pages.  You can get an overview using the \R{} command
    \code{help(package="lattice")}. 
  \item A good source of several lattice plots along with the code that produced
    them is \url{http://lmdvr.r-forge.r-project.org}.
  \item \textit{Multivariate Data Visualization with R} by Deepayan
    Sarkar the author of \Rpackage{lattice}.  See
    \url{http://lmdvr.r-forge.r-project.org/}.
\end{itemize} 
%1
\begin{figure}
     \centering
          \includegraphics[width=.6\textwidth]{basicXYPlotPrint}
   \caption{Concentration of Indomethicin over time produced using
     \Rfunction{xyplot} }
   \label{basicXYPlotPrint}
\end{figure}
%2
\begin{figure}
     \centering
          \includegraphics[width=.6\textwidth]{xyPlotCondPrint}
   \caption{Concentration of Indomethicin over time
        using \Robject{Subject} as the conditioning variable
        \Rfunction{xyplot} } 
   \label{xyPlotCondPrint}
\end{figure}
%3
\begin{figure}
     \centering
          \includegraphics[width=.6\textwidth]{xyPlotGroupingPrint}
   \caption{Concentration vs Time of Indomethicin for 6
       subjects using the Grouping variable \Robject{Subject}.}
   \label{xyPlotGroupingPrint}
\end{figure}

\begin{figure}
     \centering
          \includegraphics[width=.6\textwidth]{bwPlotPrint}
   \caption{Concentration vs Time of Indomethicin for 6
       subjects using the Grouping variable \Robject{Subject}.}
   \label{bwPlotPrint}
\end{figure}

\section{Session information}

<<sessionInfo, results=tex, echo=FALSE>>=
toLatex(sessionInfo())
@

\end{document}
