\documentclass{beamer}
\setbeamertemplate{navigation symbols}{}
% \usetheme{Copenhagen}
% \usetheme{Warsaw}
\usetheme{default}
\useinnertheme{rounded}
\useinnertheme{circles}
\useoutertheme{headshadow}
\usecolortheme{orchid}
\usecolortheme{whale}

\setbeamercolor{item}{fg=black}

\usepackage{calc}
\usepackage{alltt}
\usepackage{Sweave}
\usepackage{boxedminipage}
\usepackage{ulem}
\usepackage{hyperref}
\usepackage{fancyvrb}
\usepackage{animate}

\newcommand{\R}{{\sffamily R}}

\DeclareFixedFont{\almosttiny}{OT1}{cmr}{m}{n}{6}

\renewcommand{\emph}[1]{{\bfseries #1}}
\newcommand{\pkg}[1]{{\bfseries #1}}
\newcommand{\code}[1]{{\ttfamily #1}}
\newcommand{\dfn}[1]{{\bfseries #1}}

\definecolor{greybg}{gray}{0.9}
\definecolor{grey}{gray}{.8}
\definecolor{dkgrey}{gray}{0.5}
\newcommand{\intpic}[3]{
\setlength{\fboxsep}{.1in}
\colorbox{white}{\begin{minipage}[t]{#1}
\vspace{0pt}
\includegraphics[width=#1]{#2}
\end{minipage}\begin{minipage}[t]{\textwidth - #1 - .2in} % .2 = 2 x .1
\vspace{0pt}
\setlength{\parindent}{.1in}
\narrower
~\\
#3 \newline ~
\end{minipage}}}

\begin{document}

\SweaveOpts{keep.source = true, eps = false}

\title{Is \code{image()} Everything?}
\author{Paul Murrell}
\institute{The University of Auckland}
\date{July 2011}

\frame{\titlepage}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Raster support in R graphics}

\begin{itemize}
\item
From version 2.11.0 R has native support for \emph{raster
images}.
\begin{itemize}
\item
\code{as.raster()}
\item
\code{rasterImage()}
\item
\code{grid.raster()}
\item
prior to that, raster images were drawn as a matrix of rectangles.
\end{itemize}
\end{itemize}

\begin{itemize}
\item
So what?
\end{itemize}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{The original reason}

\begin{itemize}
\item
Do raster graphical elements the right way.
\begin{itemize}
\item
Some sorts of plots, e.g., heatmaps, contain graphical elements
that are naturally raster in nature.
\end{itemize}
\end{itemize}

<<heatmapdata, echo=FALSE, results=hide, eval=FALSE>>=
# http://www2.warwick.ac.uk/fac/sci/moac/students/peter_cock/r/heatmap
library("ALL")
data("ALL")
eset <- ALL[, ALL$mol.biol %in% c("BCR/ABL", "ALL1/AF4")]
library("limma")
f <- factor(as.character(eset$mol.biol))
design <- model.matrix(~f)
fit <- eBayes(lmFit(eset,design))
selected  <- p.adjust(fit$p.value[, 2]) < 0.05
esetSel <- eset[selected, ]
library("gplots")

<<heatmap, echo=FALSE, eval=FALSE>>=
pdf("image-heatmap.pdf")
heatmap.2(exprs(esetSel), col=redgreen(75), scale="row", 
          key=FALSE, density.info="none", dendrogram="none",
          trace="none", lwid=c(.2, 1), lhei=c(.2, 1),
          cexRow=.3)
dev.off()

<<heatmap-raster, echo=FALSE, eval=FALSE>>=
pdf("image-heatmap-raster.pdf")
heatmap.2(exprs(esetSel), col=redgreen(75), scale="row", 
          key=FALSE, density.info="none", dendrogram="none",
          trace="none", lwid=c(.2, 1), lhei=c(.2, 1),
          cexRow=.3, useRaster=TRUE)
dev.off()

@ 

\vspace*{-.2in}
\begin{center}
\includegraphics[width=.8\textwidth]{gb-2010-11-3-r24-3.pdf}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{The original reason}

\begin{itemize}
\item
Practical considerations:
\begin{itemize}
\item
Smaller files.

For example, the PDF versions of the heatmap below using rectangles
vs raster
are 45k vs 13k.

\item
Faster drawing.

Not just when \R{} produces the graphic but when viewing software renders 
the graphic.
\end{itemize}
\end{itemize}

\vspace*{-.4in}
\begin{center}
\includegraphics[width=.5\textwidth]{image-heatmap-raster}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Some bonuses}

<<heatmap-svg, echo=FALSE, eval=FALSE>>=
svg("image-heatmap-svg.svg")
heatmap.2(exprs(esetSel), col=redgreen(75), scale="row", 
          key=FALSE, density.info="none", dendrogram="none",
          trace="none", lwid=c(.2, 1), lhei=c(.2, 1),
          cexRow=.3)
dev.off()

@ 
\begin{itemize}
\item
No viewer artifacts.

(This is svg() output viewed in Firefox 3)
\end{itemize}

\begin{center}
\includegraphics[width=.5\textwidth]{image-heatmap-svg.png}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Some bonuses}

<<interp, echo=FALSE, eval=FALSE>>=
img <- readPNG(system.file("img", "Rlogo.png", package="png"))

pdf("image-logo.pdf")
library(grid)
grid.raster(img, interp=FALSE)
dev.off()

pdf("image-logo-interp.pdf")
library(grid)
grid.raster(img)
dev.off()

@

\begin{itemize}
\item
Interpolation
\end{itemize}

\hfill
\includegraphics[width=.4\textwidth]{image-logo}
\hfill
\includegraphics[width=.4\textwidth]{image-logo-interp}
\hfill

\end{frame}


%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Infographics in R}

\begin{itemize}
\item
Start to conceive of doing this sort of thing in R

(A GOOD Blog post)
\end{itemize}

\begin{center}
\includegraphics[width=.5\textwidth]{post_full_1280267275dod-iraq-2.png}
\end{center}

\end{frame}


%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Infographics in R}

\begin{itemize}
\item
It becomes simpler to think about incorporating raster images
as part of an \R{} graphics image.
\item
The raster image can not only be raster data, but also an external raster
image, such as a digital photo.
\end{itemize}

<<echo=FALSE>>=
library(grid)

options(continue="  ")

# Background data
unknown <- 8.7
total <- 9.1
known <- total - unknown

theta0 <- pi/4
thetaN <- theta0 + 2*pi*unknown/total
theta <- seq(theta0, thetaN, length.out=100)
x <- 0.3*c(0, cos(theta)) + 0.5
y <- 0.3*c(0, sin(theta)) + 0.35

<<imgbg, eval=FALSE>>=
library(png)
bg <- readPNG("AfterTheBombs.png")
library(grid)
grid.raster(bg, height=1)
@ 

<<imgpoly, eval=FALSE>>=
grid.polygon(x, y, 
             gp=gpar(col=NA, 
                     fill=rgb(.67, 0, .11, .7)))
@

<<bg, echo=FALSE, results=hide, fig=TRUE, include=FALSE, width=9.333>>=
<<imgbg>>
pushViewport(viewport(width=unit(1, "snpc"), height=unit(1, "snpc")))
<<imgpoly>>
@ 


\end{frame}


%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Infographics in R}

\begin{center}
\includegraphics{image-bg}
\end{center}

\end{frame}


%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in R}

\begin{itemize}
\item
Once we have raster images in \R{}, they are essentially just matrices.
\item
We can perform simple image processing via matrix manipulation.
\end{itemize}

<<eval=FALSE>>=
png("mask.png")
grid.polygon(x, y, gp=gpar(col=NA, fill="black"))
dev.off()

mask <- readPNG("mask.png")
maskRaster <- as.raster(mask)

bgRaster <- as.raster(bg)

bgMask <- bgRaster[maskRaster == "#000000"]
@ 

<<echo=FALSE, results=hide>>=
w <- dim(bg)[2]
h <- dim(bg)[1]

png("mask.png", width=w, height=h)
pushViewport(viewport(width=unit(1, "snpc"), height=unit(1, "snpc")))
grid.polygon(x, y, gp=gpar(col=NA, fill="black"))
dev.off()

mask <- readPNG("mask.png")
maskRaster <- as.raster(mask)

bgRaster <- as.raster(bg)

# Set the pixels under the mask so that
# (i) they keep the same alpha
# (ii) their blue and green channels are 0
# (iii) the red corresponds to the greyscale version of the original RGB
bgTemp <- bgRaster
bgTemp[maskRaster != "#000000"] <- NA

png("bgmask.png", width=w, height=h)
grid.raster(bgTemp)
dev.off()

@ 
\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in R}

\setlength\fboxsep{0pt}

\begin{center}
\fbox{\includegraphics[width=.45\textwidth]{mask}}
\includegraphics[width=.45\textwidth]{AfterTheBombs}

\fbox{\includegraphics[width=.45\textwidth]{bgmask}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in R}

<<eval=FALSE>>=
bgMaskRGB <- col2rgb(bgMask)

bgRed <- rgb((0.3*bgMaskRGB[1, ] +
              0.59*bgMaskRGB[2, ] +
              0.11*bgMaskRGB[3, ]),
             0, 0, max=255)

bgRaster[maskRaster == "#000000"] <- bgRed
@ 

<<echo=FALSE, results=hide>>=
bgMask <- bgRaster[maskRaster == "#000000"]

bgMaskRGB <- col2rgb(bgMask)
# Rough conversion to greyscale
# Y = 0.3*R + 0.59*G + 0.11*B
bgRed <- rgb((0.3*bgMaskRGB[1, ] +
              0.59*bgMaskRGB[2, ] +
              0.11*bgMaskRGB[3, ]),
             0, 0, max=255)

bgTemp[maskRaster == "#000000"] <- bgRed

png("bgred.png", width=w, height=h)
grid.raster(bgTemp)
dev.off()

bgRaster[maskRaster == "#000000"] <- bgRed

png("bgraster.png", width=w, height=h)
grid.raster(bgRaster)
dev.off()

@ 
\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in R}

\setlength\fboxsep{0pt}

\begin{center}
\fbox{\includegraphics[width=.45\textwidth]{bgmask}}
\fbox{\includegraphics[width=.45\textwidth]{bgred}}

{\includegraphics[width=.45\textwidth]{bgraster}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{}

<<onhold, echo=FALSE, eval=FALSE>>=
headText <-
    "The Department of Defense is unable to account for the use of
$8.7 billion of the $9.1 billion it spent on reconstruction in Iraq"
heading <- textGrob(headText,
                    x=unit(0.5, "cm"),
                    y=unit(3, "lines"),
                    just=c("left", "top"),
                    gp=gpar(col="white"))
pushViewport(viewport(gp=gpar(cex=.8)),
             viewport(x=0.05, y=1,
                      just=c("left", "top"),
                      height=grobHeight(heading) + unit(4, "lines"),
                      width=grobWidth(heading) + unit(1, "cm")))
grid.rect(gp=gpar(fill="black"))
grid.segments(x0=unit(0.5, "cm"),
              x1=unit(1, "npc") - unit(0.5, "cm"),
              y0=unit(1, "npc") - unit(2, "lines"),
              y1=unit(1, "npc") - unit(2, "lines"),
              gp=gpar(col="grey50", lwd=2))
grid.text("That's 96 Percent",
          x=unit(0.5, "cm"),
          y=unit(1, "npc") - unit(1, "lines"),
          just="left",
          gp=gpar(fontface="bold", col="white"))
grid.draw(heading)
popViewport(2)
@

\begin{center}
\includegraphics{IraqAid.png}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in R}

\begin{itemize}
\item
There is always a danger that people will get carried away
with this sort of feature ...
\end{itemize}

\begin{center}
\animategraphics[autoplay,height=2in]{10}{Mark/animation}{1}{162} 
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in plots}

\begin{itemize}
\item
... but there are also some serious applications.

For example, a plot with a legend that has a ``blank'' background.
\end{itemize}

<<echo=FALSE, results=hide>>=
cols <- hcl(seq(0, 240, 120), 80, 70)

png("plot.png", bg="grey90")
with(iris,
     {
         plot(Sepal.Length, Sepal.Width, type="n")
         grid(lty="solid", lwd=3)
         points(Sepal.Length, Sepal.Width,
                bg=cols[Species], pch=21)
         box()
     })
dev.off()

png("legendplot.png", bg="grey90")
with(iris,
     {
         plot(Sepal.Length, Sepal.Width, type="n")
         grid(lty="solid", lwd=3)
         points(Sepal.Length, Sepal.Width,
                bg=cols[Species], pch=21)
         box()
         legend(6.25, 4.4, legend=levels(Species), 
                pch=21, col="black", pt.bg=cols, 
                bg="transparent",
                box.lwd=3, cex=1.5)
     })
dev.off()

png("legendbad.png", bg="grey90")
with(iris,
     {
         plot(Sepal.Length, Sepal.Width, type="n")
         grid(lty="solid", lwd=3)
         points(Sepal.Length, Sepal.Width,
                bg=cols[Species], pch=21)
         box()
         legend(6.25, 4.4, legend=levels(Species), 
                pch=21, col="black", pt.bg=cols, 
                bg="white",
                box.lwd=3, cex=1.5)
     })
dev.off()

png("legendmask.png", bg="grey90")
with(iris,
     {
         plot(Sepal.Length, Sepal.Width, type="n",
              ann=FALSE, axes=FALSE)
         legend(6.25, 4.4, legend=levels(Species), 
                pch=21, col="black", pt.bg="black", 
                bg="black",
                box.lwd=3, cex=1.5)
     })
dev.off()

png("legendkey.png", bg="grey90")
with(iris,
     {
         plot(Sepal.Length, Sepal.Width, type="n",
              ann=FALSE, axes=FALSE)
         legend(6.25, 4.4, legend=levels(Species), 
                pch=21, col="black", pt.bg=cols, 
                box.lwd=3, cex=1.5)
     })
dev.off()

legendplot <- as.raster(readPNG("legendplot.png"))
legendmask <- as.raster(readPNG("legendmask.png"))
legendkey <- as.raster(readPNG("legendkey.png"))

legendpunch <- legendplot
legendpunch[legendmask == "#000000"] <- "transparent"

legendfinal <- legendplot
legendfinal[legendmask == "#000000"] <- 
    legendkey[legendmask == "#000000"]

png("legendpunch.png")
grid.rect(gp=gpar(col=NA, fill="grey90"))
grid.raster(legendpunch, interpolate=FALSE)
dev.off()

png("legendfinal.png")
grid.rect(gp=gpar(col=NA, fill="grey90"))
grid.raster(legendfinal, interpolate=FALSE)
dev.off()


@ 

\begin{center}
\fbox{\includegraphics[width=.5\textwidth]{legendfinal.png}}
\end{center}

\end{frame}


%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in plots}

\begin{itemize}
\item
A transparent background for the legend is not sufficient.
\end{itemize}

\begin{center}
\fbox{\includegraphics[width=.5\textwidth]{legendplot.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in plots}

\begin{itemize}
\item
A solid colour background for the legend is not a good
general solution.
\end{itemize}

\begin{center}
\fbox{\includegraphics[width=.5\textwidth]{legendbad.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in plots}

\begin{verbatim}
plot(Sepal.Length, Sepal.Width)
\end{verbatim}

\begin{center}
\fbox{\includegraphics[width=.5\textwidth]{plot.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in plots}

\begin{verbatim}
plot.new()
legend(bg="transparent")
\end{verbatim}

\begin{center}
\fbox{\includegraphics[width=.5\textwidth]{legendkey.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in plots}

\begin{verbatim}
plot.new()
legend(bg="black")
\end{verbatim}

\begin{center}
\fbox{\includegraphics[width=.5\textwidth]{legendmask.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in plots}

\begin{verbatim}
plot[legendMask == "black"] <- "transparent"
\end{verbatim}

\begin{center}
\fbox{\includegraphics[width=.5\textwidth]{legendpunch.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Image processing in plots}

{\small
\begin{verbatim}
plot[legendMask == "black"] <- legend[legendMask == "black"]
\end{verbatim}
}

\begin{center}
\fbox{\includegraphics[width=.5\textwidth]{legendfinal.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}

\begin{itemize}
\item
It can be useful to arrange images using \R{} graphics facilities.
\begin{itemize}
\item
For example, arrange images using \pkg{grid} coordinate
systems.
\end{itemize}
\end{itemize}

\begin{verbatim}
grid.raster(server, y=.7, 
            width=unit(7, "mm"))
grid.raster(hub, x=c(.4, .6), 
            width=unit(1, "cm"))
grid.raster(pc, x=c(.2, .8, .8), y=c(.5, .7, .4), 
            width=unit(1, "cm"))
grid.raster(printer, x=c(.4, .6), y=.2, 
            width=unit(12, "mm"))
\end{verbatim}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}

\begin{itemize}
\item
Cisco Network Icons.
\end{itemize}

\vspace{.2in}

\hspace*{\fill}
{\includegraphics[width=.07\textwidth]{{Cisco/server.png}}}
\hfill
{\includegraphics[width=.1\textwidth]{Cisco/pc.jpg}}
\hfill
{\includegraphics[width=.12\textwidth]{Cisco/printer.jpg}}
\hfill
{\includegraphics[width=.1\textwidth]{Cisco/hub.jpg}}
\hspace*{\fill}

\vspace{.2in}

\hspace*{\fill}
{\includegraphics[width=.1\textwidth]{Cisco/ata.jpg}}
\hfill
{\includegraphics[width=.12\textwidth]{Cisco/sattelite.jpg}}
\hfill
{\includegraphics[width=.12\textwidth]{Cisco/pmc.jpg}}
\hfill
{\includegraphics[width=.1\textwidth]{Cisco/AXP.jpg}}
\hspace*{\fill}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}


<<network, echo=FALSE, results=hide, fig=TRUE, include=FALSE>>=
pc <- readPNG("Cisco/pc.png")
hub <- readPNG("Cisco/hub.png")
server <- readPNG("Cisco/server.png")
printer <- readPNG("Cisco/printer.png")
# grid.newpage()
grid.curve(.5, .7, .4, .5, curvature=-1)
grid.curve(.5, .7, .6, .5, curvature=-1)
grid.segments(.4, .5, .2, .5)
grid.segments(.4, .5, .4, .2)
grid.curve(.6, .5, .8, .7, curvature=1)
grid.curve(.61, .5, .8, .4, curvature=1)
grid.segments(.6, .5, .6, .2)
grid.raster(server, y=.7, width=.07)
grid.raster(hub, x=c(.4, .6), width=.1)
grid.raster(pc, x=c(.2, .8, .8), y=c(.5, .7, .4), width=.1)
grid.raster(printer, x=c(.4, .6), y=.2, width=.12)
@ 

% nicked from
% http://stackoverflow.com/questions/4975681/r-creating-graphs-where-the-nodes-are-images/4978111#4978111

<<graph, echo=FALSE, results=hide, fig=TRUE, include=FALSE>>=
set.seed(1)
adj <- matrix(sample(0:1,10^2,T,prob=c(0.8,0.2)),10,10)
library('qgraph')
L <- qgraph(adj,borders=FALSE,vsize=0,labels=F,directed=F)$layout
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
apply(L,1,function(x)rasterImage(img,x[1]-0.1,x[2]-0.1,x[1]+0.1,x[2]+0.1))
@ 
%$

\begin{center}
{\includegraphics[width=.8\textwidth]{image-network}}
\end{center}


\end{frame}
%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}

\begin{itemize}
\item
It can be useful to arrange images using \R{} graphics facilities.
\begin{itemize}
\item
For example, arrange images using \pkg{grid} viewports and layouts.
\end{itemize}

<<lay, eval=FALSE>>=
imageLayout <- 
    grid.layout(4, 5,
                widths=c(2, 1.5, 2, 1, 2.5),
                heights=c(2.5, .5, 2, 1),
                respect=TRUE)
@ 
\end{itemize}

<<layout, echo=FALSE, fig=TRUE, include=FALSE, width=6, height=4>>=
<<lay>>
margin <- unit(20, "mm")
pushViewport(viewport(width=unit(1, "npc") - margin,
                      height=unit(1, "npc") - margin,
                      layout=imageLayout))
for (i in 1:4) {
    for (j in 1:5) {
        pushViewport(viewport(layout.pos.col=j, layout.pos.row=i))
        grid.rect()
        popViewport()
    }
}

@ 

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}

\begin{center}
\fbox{\includegraphics[width=.8\textwidth]{image-layout}}
\end{center}


\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}

\begin{itemize}
\item
Holiday snaps.
\end{itemize}

\vspace{.2in}

\begin{center}
{\includegraphics[width=.2\textwidth]{treeThumb.jpg}}
\hfill
{\includegraphics[width=.2\textwidth]{ropeThumb.jpg}}
\hfill
{\includegraphics[width=.2\textwidth]{hillThumb.jpg}}
\hfill
{\includegraphics[width=.2\textwidth]{rockThumb.jpg}}

\vspace{.2in}

{\includegraphics[width=.2\textwidth]{sandThumb.jpg}}
\hfill
{\includegraphics[width=.2\textwidth]{gullThumb.jpg}}
\hfill
{\includegraphics[width=.2\textwidth]{signThumb.jpg}}
\hfill
{\includegraphics[width=.2\textwidth]{pohuThumb.jpg}}
\hfill
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}

<<treepos, eval=FALSE>>=
pushViewport(viewport(layout.pos.col=1, 
                      layout.pos.row=1))
grid.raster(treeMatrix, width=2)
@ 

<<tree, echo=FALSE, results=hide, fig=TRUE, width=6, height=4>>=
tree <- readPNG("treeThumb.png")
treeRaster <- as.raster(tree)
treeRGB <- col2rgb(treeRaster)
treeMatrix <- t(matrix(rgb(treeRGB[1, ],
                           treeRGB[2, ],
                           treeRGB[3, ],
                           100, max=255),
                       ncol=dim(tree)[1],
                       nrow=dim(tree)[2]))

grid.newpage()
<<layout>>
<<treepos>>
grid.rect(gp=gpar(lwd=3))

@ 
\vspace{.2in}
\begin{center}
\includegraphics[width=.8\textwidth]{image-tree}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}

<<sandpos, eval=FALSE>>=
pushViewport(viewport(layout.pos.col=1:3, 
                      layout.pos.row=4))
grid.raster(sandMatrix, width=1, height=1.5, 
            y=0, just="bottom")
@ 

<<sand, echo=FALSE, results=hide, fig=TRUE, width=6, height=4>>=
sand <- readPNG("sandThumb.png")
sandRaster <- as.raster(sand)
sandRGB <- col2rgb(sandRaster)
sandMatrix <- t(matrix(rgb(sandRGB[1, ],
                           sandRGB[2, ],
                           sandRGB[3, ],
                           100, max=255),
                       ncol=dim(sand)[1],
                       nrow=dim(sand)[2]))

grid.newpage()
<<layout>>
<<sandpos>>
grid.rect(gp=gpar(lwd=3))

@ 
\begin{center}
\includegraphics[width=.8\textwidth]{image-sand}
\end{center}


\end{frame}


%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in R}

\setlength\fboxsep{0pt}
\begin{center}
\fbox{\includegraphics[width=.8\textwidth]{tealbay.jpg}}
\end{center}


\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{itemize}
\item
Again, there are more serious applications.
\end{itemize}

\begin{center}
{\includegraphics[width=.6\textwidth]{mapoverlay.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{itemize}
\item
We want to combine this image (light source data from NASA) ...
\end{itemize}

\begin{center}
{\includegraphics[width=.6\textwidth]{test.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{itemize}
\item
... as plotted by R (the \pkg{raster} package) ...
\end{itemize}

\begin{center}
{\includegraphics[width=.6\textwidth]{rasterplot}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{itemize}
\item
... with this image (Google Map tile).
\end{itemize}

\begin{center}
{\includegraphics[width=.5\textwidth]{staticmap.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{itemize}
\item
The important bit is getting the coordinate systems lined up.
\end{itemize}

<<eval=FALSE>>=
library(raster)
light <- raster("light.tif")
@ 

<<eval=FALSE>>=
plot(light, maxpixels=(640*640),
     col="transparent")
@ 

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{center}
{\includegraphics[width=.6\textwidth]{rastersetup}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{itemize}
\item
The important bit is getting the coordinate systems lined up.
\end{itemize}

<<eval=FALSE>>=
gmap <- GetMap(c(40.78, -4.02), 
               zoom=9, size=c(485, 485),
               maptype="satellite", format="png32",
               destfile="gmaptile.png")
gmaptile <- readPNG("gmaptile.png")
gmaprange <- XY2LatLon(gmap, 
                       c(-485/2, 485/2), 
                       c(-485/2, 485/2))
@ 

<<eval=FALSE>>=
rasterImage(gmaptile, 
            gmaprange[1, 2], gmaprange[1, 1],
            gmaprange[2, 2], gmaprange[2, 1])
@ 

<<echo=FALSE, results=hide>>=
# Static map from 
# http://maps.google.com/maps/api/staticmap?center=40.78,-4.02&zoom=9&size=485x485&maptype=satellite&format=png32&sensor=true

# NOTE Google's terms of service don't really cover this sort of use
# http://www.google.com/permissions/guidelines.html
# unless maybe it's put on the web

# NOTE that this covers the range ...
# Longitude: -4.68841552734375  -3.3563232421875
# Latitude: 40.27533480732468  41.28399850538595
# (see googleMapExtent.html)
# Should also be able to calc that using XY2LatLon() in 'RGoogleMaps' (?)

gmap <- readPNG("staticmap.png")

library(raster)
Lon  <- -4.02
Lat  <- 40.78
Test <-raster("test.tif")

pdf("rasterplot.pdf")
plot(Test, maxpixels=(640*640))
dev.off()

pdf("rastersetup.pdf")
# Set up the coordinate system
plot(Test, maxpixels=(640*640), col="transparent")
dev.off()

png("maparrange.png", width=2100, height=2100, res=300)
# Set up the coordinate system
plot(Test, maxpixels=(640*640), col="transparent")
# Draw the google map in the plot region
rasterImage(gmap, 
            -4.68841552734375, 40.27533480732468,
            -3.3563232421875, 41.28399850538595)
dev.off()

png("mapoverlay.png", width=2100, height=2100, res=300)
# Set up the coordinate system
plot(Test, maxpixels=(640*640), col="transparent")
# Draw the google map in the plot region
rasterImage(gmap, 
            -4.68841552734375, 40.27533480732468,
            -3.3563232421875, 41.28399850538595)
# Redo original plot, WITH semitransparent colours
par(new=TRUE)
plot(Test, maxpixels=(640*640),
     col=c("transparent",
       adjustcolor(colorRampPalette(c("white", 
                                      "red"))(10),
                   alpha.f=.3)))
contour(Test, add=TRUE)
dev.off()

@ 
\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{center}
{\includegraphics[width=.6\textwidth]{maparrange.png}}
\end{center}

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{itemize}
\item
The final result requires the original plot to
be redrawn.\\
Contour lines are also added.
\end{itemize}

<<eval=FALSE>>=
par(new=TRUE)
colorPalette <- 
    colorRampPalette(c("white", "red"))
plot(light, maxpixels=(640*640),
     col=c("transparent",
           adjustcolor(colorPalette(10),
                       alpha.f=.3)))
contour(light, add=TRUE)
@ 

\end{frame}

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Arranging images in plots}

\begin{center}
{\includegraphics[width=.6\textwidth]{mapoverlay.png}}
\end{center}

\end{frame}


%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Summary}

\begin{itemize}
\item
Native support for raster images leads to faster drawing and smaller 
graphics files.
\item
We can start to think about \R{} graphics as image manipulation software,
 which leads to things like infographics.
\item
Can use \R{} graphics features to arrange graphical images,
which is particularly useful for incorporating raster images
within plots.
\end{itemize}

\end{frame}


%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{Acknowledgements}

{\small
\begin{itemize}
\item
The opening raster image is from an open access article at
Biomed Central (provided by Wolfgang Huber).
\item
The original blog post was by Morgan Clendaniel\\
\url{http://www.good.is/post/infographic-where-did-the-money-to-rebuild-iraq-go/}
\item
The background image used in the remake is ``After the Bombs'' by
Adam Henning\\
\url{http://www.flickr.com/photos/adamhenning/66822173/}\\
CC BY-NC-SA
\item
The network icons are from Cisco\\
\url{http://www.cisco.com/web/about/ac50/ac47/2.html}
``You may use them freely, but you may not alter them.''
\item
The face animation is by and of Mark Holmes.
\item
The NASA light data is from Steve Mosher.
\item
The Google Map tile is copyright 2011 Google, Map Data and
copyright 2011 Tele Atlas (valid for use in blogs).
\end{itemize}
}

\end{frame}




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% END DOCUMENT
\end{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%
% FRAME
%%%%%%%
\begin{frame}[fragile]
\frametitle{}

\end{frame}

