%\VignetteIndexEntry{B.6 Visualizing Sequence Data}

\chapter{Visualizing Sequence Data}

\R{} has some great visualization packages; essential references
include \cite{chang2012r} for a general introduction,
Murrell~\cite{murrell2005r} for base graphics,
Sarkar~\cite{sarkar2008lattice} for \Rpackage{lattice}, and
Wickham~\cite{wickham2009ggplot2} for \Rpackage{ggplot2}. Here we take
a quick tour of visualization facilities tailored for sequence data
and using \Bioconductor{} approaches. Our focus is on \Biocpkg{Gviz};
an exercise explores interactive visualization using \Rpackage{shiny}.

\section{\Biocpkg{Gviz}}

The \Biocpkg{Gviz} package produces very elegant images organized in a
more-or-less familiar `track' format. The following exercises walk
through the \Biocpkg{Gviz}
\href{http://bioconductor.org/packages/2.12/bioc/html/Gviz.html}{User
  guide} Section 2.

\begin{Exercise}
  Load the \Biocpkg{Gviz} package and sample \Rclass{GRanges}
  containing genomic coordinates of CpG islands. Create a couple of
  variables with information on the chromosome and genome of the data
  (how can this information be extracted from the \Robject{cpgIslands}
  object?).
\end{Exercise}
<<Gviz>>=
library(Gviz)
data(cpgIslands)
chr <- "chr7"
genome <- "hg19"
@ 
%% 
The basic idea is to create a track, perhaps with additional
attributes, and to plot it. There are different types of track, and we
create these one at a time. We start with a simple annotation track
<<AnnotationTrack>>=
atrack <- AnnotationTrack(cpgIslands, name="CpG")
plotTracks(atrack)
@ 
%% 
Then add a track that represents genomic coordinates. Tracks are
combined when plotted, as a simple list. The vertical ordering
of tracks is determined by their position in the list.
<<GenomeAxisTrack>>=
gtrack <- GenomeAxisTrack()
plotTracks(list(gtrack, atrack))
@ 
%% 
We can add an ideogram to provide overall orientation\ldots
<<IdeogramTrack>>=
itrack <- IdeogramTrack(genome=genome, chromosome=chr)
plotTracks(list(itrack, gtrack, atrack))
@
%% 
and a more elaborate gene model, as an \Rclass{data.frame} or
\Rclass{GRanges} object with specific columns of metadata.
<<GeneRegionTrack>>=
data(geneModels)
grtrack <- 
    GeneRegionTrack(geneModels, genome=genome,
                    chromosome=chr, name="Gene Model")
tracks <- list(itrack, gtrack, atrack, grtrack)
plotTracks(tracks)
@ 
%% 
Zooming out changes the location box on the ideogram
<<Gviz-zoom>>=
plotTracks(tracks, from=2.5e7, to=2.8e7)
@ 
%% 
When zoomed in we can add sequence data
<<Gviz-sequence>>=
library(BSgenome.Hsapiens.UCSC.hg19)
strack <- SequenceTrack(Hsapiens, chromosome=chr)
plotTracks(c(tracks, strack), from=26450430, to=26450490, cex=.8)
@ 

As the \Biocpkg{Gviz} vignette humbly says, `so far we have replicated
the features of a whole bunch of other genome browser tools out
there`. We'd like to be able integrate our data into these plots, with
a rich range of plotting options. The key is the \Rfunction{DataTrack}
function, which we demonstrate with some simulated data; this final
result is shown in Figure~\ref{fig:GvizFinal}.
<<Gviz-data>>=
## some data
lim <- c(26700000, 26900000)
coords <- seq(lim[1], lim[2], 101)
dat <- runif(length(coords) - 1, min=-10, max=10)

## DataTrack
dtrack <- 
    DataTrack(data=dat, start=coords[-length(coords)],
              end= coords[-1], chromosome=chr, genome=genome,
              name="Uniform Random")
plotTracks(c(tracks, dtrack))
@
%% 
<<Gviz-figure, echo=FALSE>>=
pdf("GvizFigure.pdf")
plotTracks(c(tracks, dtrack))
xx <- capture.output(dev.off())
@ 
Section~4.3 of the \Biocpkg{Gviz} vignette illustrates flexibility of
the data track.

\begin{figure}
  \centering
  \caption{\Biocpkg{Gviz} ideogram, genome coordinate, annotation, and data tracks.}
  \label{fig:GvizFinal}
  \includegraphics[width=.6\textwidth, height=!]{GvizFigure}
\end{figure}

\section{\Biocpkg{ggbio}}

The \Biocpkg{ggbio} package complements facilities in
\Biocpkg{Gviz}. It uses the central metaphors of the `grammar of
graphics' made popular by the \Rpackage{ggplot2} package, and
integrates closely with the \Bioconductor{} ranges infrastructure. For
example, the \Rfunction{autoplot} function applied to a
\Biocpkg{Rsamtools} \Rclass{BamFile} instances results in a coverage
plot. In addition to the grammar of graphics approach, the package
offers a wider range of plots, for instance circular plots. The use of
the package is covered in it's vignette.


\section{\Rpackage{shiny} for easy interactive reports}

As a final example of visualization, the \Rpackage{shiny} package and
web site\footnote{\url{http://www.rstudio.com/shiny/}} has recently
been introduced. It offers a new model for developing interactive,
browser-based visualizations. These visualizations could be an
excellent way to provide sophisticated exploratory or summary analysis
in a very accessible way. The idea is to write a `user interface'
component that describes how a page is to be presented to users, and a
`server' that describes how the data are to be calculated or modified
in responses to user choices. The programming model is `reactive',
where changes in a user choice automatically trigger re-calculations
in the server. This reactive model is like in a spreadsheet with a
formula, where adjusting a cell that the formula references triggers
re-calculation of the formula. As with a spreadsheet, someone creating
a \Rpackage{shiny} application does not have to work hard to make
reactivity work.

\begin{Exercise}
  We explore \Rpackage{shiny} by creating a simple application based
  on the \Biocannopkg{parathyroidSE} package. Start by copying the
  directory returned by
<<shiny-loc, eval=FALSE>>=
system.file(package="Morgan2013", "shiny")
@ 
%% 
to a convenient location on your disk, e.g., \texttt{~/shiny}. Start
\R{} and evaluate the commands
<<shiny-server, eval=FALSE>>=
library(shiny)
runApp("~/shiny/se-app0")
@ 
%% 
Where the path is correct for the location where you placed the
\texttt{shiny} folder. This should launch a web browser, with a simple
\Rpackage{shiny} application.

Add features to the user interface. Do this by adding commands to the
file \texttt{~/shiny/se-app0/ui.R} in the \Rfunction{sidebarPanel}
function. Add: (a) a \Rfunction{checkboxInput} to indicate that the
user would like to see the experiment data; and (b) a
\Rfunction{checkboxInput} to indicate that the user would like to see
the column (sample) data. Add some output to \Rfunction{mainPanel}, in
particular \Rfunction{verbatimTextOutput} for an overview of a
\Rclass{SummarizedExperiment}. Use the \Rpackage{shiny} help pages and
\texttt{~/shiny/se-app1/ui.R} as a guide to correct syntax. 

Re-load the browser page of the shiny app to check that the changes
you have made are correct.

Add functionality to the \texttt{~/shiny/se-app0/server.R}. Start by
loading the \Biocannopkg{parathyroidSE} data package. Then update the
body of \Rfunction{shinyServer} by: (a) writing a \Rfunction{reactive}
code chunk that evaluates \Rcode{data(parathyroidGenesSE)} to load the
data in to \R{}, and then returns the \Robject{parathyroidGenesSE}
object; (b) a \Rfunction{renderPrint} code chunk that assigns to the
\Robject{output} list the result of \Rfunction{print}'ing the object
returned by the reactive function; and (c) additional
\Rfunction{renderPrint} and \Rfunction{renderTable} functions to
finish the implementation of the server. Consult the \Rpackage{shiny}
package and \texttt{~/shiny/se-app1/server} file for the correct
syntax.

`Kill' the running app (cntrl-C in the \R{} session in which is was
created?), and reload the app with \Rcode{runApp("~/shiny/se-app0")}.

Add additional functionality that would help the user to understand
the data present in the \Robject{parathyroidGenesSE} instance.
\end{Exercise}
