# Capítulo 2. Análisis exploratorio y
#   representación gráfica de datos
#  2.1. Una introducción a los gráficos con R
#  2.1.1. El sistema de gráficos en R

x <- rnorm(100)
hist(x)
library(lattice)
histogram(x)

#  2.1.2. Formatos básicos de gráficos

library(ADER)
data(Lucanus)
str(Lucanus)
plot(KB~EL, data=Lucanus, xlab="Longitud de élitros (mm)",
  ylab="Anchura de cabeza (mm)")
text(20, 22, "Relaciones alométricas\nen ciervo volante")

plot(KB~EL, data=Lucanus)
plot(Lucanus$KB~Lucanus$EL)
plot(Lucanus$EL,Lucanus$KB)
plot(Lucanus[, 1:2])
with(Lucanus, plot(EL, KB))
with(Lucanus, plot(KB~EL))

y <- rnorm(20)
par(mfrow=c(2,2))
plot(y, type="p")
plot(y, type="l")
plot(y, type="b")
plot(y, type="h")

#  2.1.3. Dispositivos gráficos

jpeg(file="grafico1.jpeg")
plot(KB~EL, data=Lucanus)
dev.off()

pdf(file="grafico1.pdf")
plot(KB~EL, data=Lucanus)
dev.off()

help(pdf)

jpeg(file="grafico1.jpg", bg="yellow", width=300, height=500)
plot(KB~EL, data=Lucanus)
dev.off()

jpeg(file="grafico%03d.jpeg")
for(i in 1:20){
   plot(KB~EL, data=Lucanus, pch=i, main=paste("pch =", i))
}
dev.off()

pdf(file="grafico%03d.pdf", onefile=FALSE)
for(i in 1:20){
   plot(KB~EL, data=Lucanus, pch=i, main=paste("pch =", i))
}
dev.off()



#  Cuadro 2.1. Tamaño y resolución de imágenes

plot(KB~EL, Lucanus, pch=19)

windows(height=6, width=6, pointsize=16)
plot(KB~EL, Lucanus, pch=19)

jpeg(file="Lucanus_15in.jpeg", width=15, height=15, units="in",
  res=300, quality=100, pointsize=12*15/7)
plot(KB~EL, Lucanus, pch=19)
dev.off()

jpeg(file="Lucanus_15cm.jpeg", width=15, height=15, units="cm",
  res=300, quality=100, pointsize=12*(15/2.54)/7)
plot(KB~EL, Lucanus, pch=19)
dev.off()


#  2.1.4. Representación de gráficos múltiples

m1 <- matrix(c(1,2,3,3), nrow=2, ncol=2)
layout(m1, heights=c(1,2), widths=c(1,1))
layout.show(3)

m2 <- matrix(c(1,3,0,2), nrow=2, ncol=2)
layout(m2, heights=c(1,3), widths=c(3,1))
layout.show(3)

data(iris)
m2 <- matrix(c(1,3,0,2), nrow=2, ncol=2)
layout(m2,heights=c(1, 3), widths=c(3, 1))
par(mar=c(1,4.1,2.1,0))
boxplot(Sepal.Width~Species, data=iris, horizontal=TRUE,
  axes=F, xlab="", ylab="", col=1:3)

par(mar=c(4.1,1,1,2.1))
boxplot(Sepal.Length~Species, data=iris, horizontal=FALSE,
  axes=F, xlab="",ylab="",col=1:3)

par(mar=c(4.1,4.1,1,0))
plot(Sepal.Length~Sepal.Width, data=iris, col=as.numeric(iris$Species),
  pch=19, xlab="Anchura (mm)", ylab="Longitud (mm)")

#  2.1.5. Funciones gráficas de bajo nivel

plot(Lucanus$EL, Lucanus$KB)
locator()
identify(Lucanus$EL, Lucanus$KB)

#  2.2. Ejemplos de análisis exploratorio
#  2.2.1. Datos continuos univariados: distribuciones de
#           frecuencias

hist(Lucanus$KB, xlab="Anchura de la cabeza (mm)",
  ylab="Frecuencia", main="")
ylab <- "Frecuencia"
xlab <- "Anchura de la cabeza (mm)"

corte5 <- seq(min(Lucanus$KB), max(Lucanus$KB), length.out=6)
hist(Lucanus$KB, breaks=corte5, xlab=xlab, ylab=ylab, main="")

corte20 <- seq(min(Lucanus$KB), max(Lucanus$KB), length.out=21)
hist(Lucanus$KB, breaks=corte20, xlab=xlab, ylab=ylab, main="")

par(mar=c(4,2,1,0.5))
stripchart(Lucanus$KB, method='stack', pch=19, cex=.8,
  xlab="Anchura de la cabeza (mm)")

par(mar=c(4,6,1,1), las=1)
boxplot(Sepal.Length~Species, data=iris, horizontal=TRUE,
  xlab='Longitud de sépalos (mm)', ylab='')

par(mar=c(4,4,1,1))
boxplot(Lucanus[,c("KB","EL")], las=1, horizontal=TRUE,
  names=c("Cabeza", "Élitros"), xlab="Tamaño (mm)")

library(scales)
par(mar=c(4,4,1,1))
nombres <- c("Cabeza", "Élitros")
boxplot(Lucanus[,c("KB","EL")], las=1, horizontal=TRUE,
  names=nombres, xlab="Tamaño (mm)")

stripchart(Lucanus[,c("KB","EL")], method='stack', pch=19,
  cex=0.6, col=alpha("grey", .4), add=T)


#  2.2.2. Datos continuos bivariados: examinando relaciones
#           entre variables

library(ADER)
data(dry)
par(mfrow=c(1,2))
xlab <-"Productividad media (NDVI)"
ylab <- "Riqueza de árboles"

with(dry, plot(ndvi, richness, xlab=xlab, ylab=ylab,
  pch=16, col="grey"))

with(dry, plot(ndvi, richness, xlab=xlab, ylab=ylab,
  pch=16, col="grey"))
lines(smooth.spline(dry$richness~dry$ndvi, df=3), lwd=2)

#   2.2.3. Extensión de técnicas bivariadas a datos multivariados

library(ADER)
data(plantulas0)
str(plantulas0)
pairs(plantulas0[plantulas0$Censo=="marzo", 3:6])

panel.cor <- function(x, y, digits=2, prefix="", cex.cor, ...) {
   usr <- par("usr")
   on.exit(par(usr))
   par(usr=c(0, 1, 0, 1))
   r <- cor(x, y)
   txt <- format(c(r, .123456789), digits=digits)[1]
   txt <- paste0(prefix, txt)
   if(missing(cex.cor))
   cex.cor <- .8/strwidth(txt)
   text(.5, .5, txt, cex=cex.cor*r)
}

pairs(plantulas0[plantulas0$Censo=="marzo", 3:6],
  upper.panel=panel.cor)

panel.hist <- function(x, ...) {
   usr <- par("usr")
   on.exit(par(usr))
   par(usr = c(usr[1:2],0,1.5))
   h <- hist(x, plot=FALSE)
   breaks <- h$breaks
   nB <- length(breaks)
   y <- h$counts
   y <- y/max(y)
   rect(breaks[-nB], 0, breaks[-1], y, col="grey", ...)
}

pairs(plantulas0[plantulas0$Censo=="marzo", 3:6],
  upper.panel=panel.cor,
  diag.panel=panel.hist,
  lower.panel=panel.smooth)

library(corrgram)
corrgram(plantulas0[plantulas0$Censo=="marzo", 3:6],
  lower.panel=panel.pts,
  upper.panel=panel.conf,
  diag.panel=panel.density)

library(scatterplot3d)
scatterplot3d(plantulas0[plantulas0$Censo=="marzo", 3:5],
  xlab="Número de hojas", ylab="Tamaño (cm)",
  zlab="Número de vecinos en 5 cm", pch=16)

#   2.2.4. Datos cuantitativos agrupados y datos cualitativos

barplot(table(plantulas0$MSET))
Tjun.means <- with(plantulas0, tapply(Tjun, list(MSET, Censo), mean))
par(mfrow=c(1,2))
par(mar=c(2,2.5,1.5,1))
barplot(Tjun.means, legend=rownames(Tjun.means), beside=TRUE,
  args.legend=list(x=16, y=2.3), las=1)

barplot(Tjun.means, legend=FALSE, las=1)

bp <- barplot(Tjun.means, legend=rownames(Tjun.means), beside=T,
  ylim=c(0,2.3), ylab="Tamaño promedio de plántula (cm)", las=1)

library(plotrix)
Tjun.se <- with(plantulas0, aggregate(Tjun, list(MSET, Censo),
  std.error))
dispersion(bp, Tjun.means, Tjun.se$x, display.na=F, arrow.gap=0)

dotchart(Tjun.means, pch=19)

library(Hmisc)
Tjun.means2 <- with(plantulas0,
  aggregate(Tjun, list(MSET, Censo), mean))

summaryD(x~Group.2+Group.1, data=Tjun.means2,
  xlab="Tamaño promedio de plántula (cm)",symbol=19)

Tjun.means2 <- with(plantulas0, aggregate(Tjun, list(MSET, Censo),
  mean))
Tjun.sd2 <- with(plantulas0, aggregate(Tjun, list(MSET, Censo),sd))
Tjun.n2 <- with(plantulas0, aggregate(Tjun, list(MSET, Censo),length))
Tjun.means2$sel <- Tjun.means2$x+(Tjun.sd2$x/sqrt(Tjun.n2$x))
Tjun.means2$ser <- Tjun.means2$x-(Tjun.sd2$x/sqrt(Tjun.n2$x))
dotchart3(cbind(Tjun.means2$sel, Tjun.means2$x, Tjun.means2$ser),
  labels=Tjun.means2$Group.1, groups=Tjun.means2$Group.2,
  pch=c(93,19,91), xlab="Tamaño promedio de plántula (cm)")


#  2.3. Gráficos condicionados del paquete lattice

library(lattice)
xyplot(Hjun~Tjun|MSET, data=plantulas0, xlab="Tamaño de plántula (cm)",
ylab="Número de hojas")

xysmooth<- function(x,y){
   panel.xyplot(x,y)
   panel.spline(x,y)
}

xyplot(Hjun~Tjun|MSET, data=plantulas0, panel=xysmooth,
  xlab="Tamaño de plántula (cm)", ylab="Número de hojas")

ls(pos="package:lattice", pat="^panel")


#  2.4. Otras soluciones gráficas: ggplot2

library(ggplot2)
p <- ggplot(plantulas0)
p + geom_point(aes(x=Tjun, y=Hjun))
p + geom_point(aes(x=Tjun, y=Hjun, shape=Censo), size=2)

ls(pos="package:ggplot2", pat="^geom_")

p + geom_point(aes(x=Tjun, y=Hjun, shape=Censo, col=Censo), size=2)+
geom_smooth(aes(x=Tjun,y=Hjun))
p + geom_point(aes(x=Tjun, y=Hjun))+
geom_smooth(aes(x=Tjun, y=Hjun), se=FALSE)+
facet_wrap(~MSET, nrow=1, scales="free")+
scale_x_continuous(name="Tamaño de plántula (cm)")+
scale_y_continuous(name="Número de hojas")+
theme_light()

ls(pos = "package:ggplot2", pat="^theme_")
