1 / 41

Gráficos en R

Gráficos en R. Seminario CEH-CEDEX 21-22 Febrero, 2011. ¿Porqué los gráficos?. 1. Simplificar lo tedioso y lo complejo . 2. A yuda visual . Concordante con los ojos . 3. Más accesible que una tabla. 4. Permite entender y memorizar mejor.

tuan
Download Presentation

Gráficos en R

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

  2. ¿Porqué los gráficos? 1. Simplificar lo tedioso y lo complejo. 2. Ayuda visual. Concordante con los ojos. 3. Más accesible que una tabla. 4. Permite entender y memorizar mejor. (William Playfair, pionero de la estadística gráfica)

  3. ¿Cuándo utilizar gráficos? • Datos < 20, presentar en una tabla. • Si hay que aclarar un gráfico con números, utilizar tabla. • Pero algunos autores discuten que la apariencia es importante… • Tufte presenta un índice para medir la cantidad de información irrelevante en un gráfico: O el % de tinta del gráfico que puede ser borrado sin afectar los datos

  4. ¿Qué hay que pedir a un gráfico? Entendibilidad 1. ¿Permite el gráfico visualizar las relaciones entre las variables? 2. ¿Interactúan los elementos (color, tamaño…) en el gráfico para maximizar nuestra percepción de las relaciones entre las variables? Claridad 1. ¿Son los elementos del gráfico claramente distinguibles? 2. ¿Son los elementos más importantes del gráfico visualmente prominentes? Consistencia 1. ¿Son los elementos de los gráficos consistentes en gráficos anteriores? 2. ¿Hay nuevos elementos que requieren una descripción adicional?

  5. ¿Qué hay que pedir a un gráfico? • Eficiencia • 1. ¿los elementos del gráfico representan eficientemente los datos? • 2. ¿Hay elementos en el gráfico que sirven a más de un propósito? • Necesidad • ¿Es el gráfico útil para representar estos datos? • ¿Es cada elemento en el gráfico necesario? • Confiabilidad • 1. ¿Están los datos adecuadamente colocados en la región de datos? • 2. ¿Están los datos representados adecuadamente por la escala?

  6. Gráficos distorsionados • Un gráfico no distorsiona si la representación visual de los datos es consistente con la representación numérica • Intrusión de diseñadores artísticos, tienden a llenar los gráficos de elementos decorativos e inútiles que distraen, ya que piensan que los datos son aburridos. Esto ocurre en periódicos y revistas del kiosco. • Gráficos tendenciosos. Ver en televisión, dependiendo del canal (elección de colores llamativos, posiciones relevantes, formas diferentes...)

  7. Gráficos distorsionados

  8. Gráficos distorsionados

  9. Gráficos distorsionados ¡¡cuidado con los gráficos que se nos presentan!!! Leer bien las escalas y las variables presentadas.

  10. Gráficos circulares (Pie Charts) Común entre personas no profesionales en estadística Si en muchas de las situaciones donde se usan se suprimieran se ahorrarían muchas hojas de papel. A veces se presenta un gráfico de pastel para mostrar que en una muestra el 50% son hombres y el 50% mujeres (?!?!?!?)

  11. Gráficos circulares (pie charts) read.table("C:/AMDDATOSR/embalses2009.txt", header=T)-> emb2009; attach(emb2009) table (tipo) = tipotable pie (tipotable, col=c(1:8), main= " Tipos Embalses")

  12. Gráficos de barras tN <- table(Ni <- stats::rpois(10000, lambda=5)) r <- barplot (tN, col=rainbow(20)) lines (r, tN, type='h', col='red', lwd=2)

  13. Boxplot o Caja de Tukey read.table("C:/AMDDATOSR/INDAGUAFLASH.txt", header=T)-> INDAGUAFLASH attach(INDAGUAFLASH) boxplot ( IBMWP ~ cuenca, col=c("yellow","blue" , "green","red" ))

  14. Boxplots o Cajas de Tukey Podemos añadir más modificaciones: boxplot ( IBMWP ~ cuenca, col=c("yellow","blue" , "green","red" ), notch = TRUE, main = "IBMWP por cuencas", ylab="IBMWP", xlab="cuenca", varwidth=T)

  15. Histogramas # Generamos 100 datos aleatorios de una Chi2 x <- rchisq(100, df = 4) hist(x, freq = FALSE, nclass=9, ylim = c(0, 0.2),col=4)

  16. Histogramas #Comparemos con la funcion de probabilidad Chi2 curve (dchisq (x, df = 4), col = 2, lty = 2, lwd = 2, add = TRUE)

  17. Histogramas read.table("C:/AMDDATOSR/embalses2008.txt", header=T)-> emb2008; attach(emb2008) hist (area, breaks = 15, ylab="nº embalses", xlab="superficie (Ha)", main="histograma de superficie de embalses", label=T, col=(palette(gray(1-seq(0,1,len=8)))))

  18. Diagramas de densidad de Kernel density (IBMWP) -> densibmwp plot (densibmwp, main= "Densidad índice IBMWP", xlab= "IBMWP", ylab= "densidad",xlim=c(0,300)) polygon (densibmwp, col=1)

  19. Representando 2 variables #EJEMPLO: DISPERSIÓN read.table ("C:/AMDDATOSR/INDAGUAFLASH.txt", header=T)-> INDAGUAFLASH attach(INDAGUAFLASH) head (INDAGUAFLASH) cuenca SITE IVAM NFAM IBMWP IASPT 1 ALEGRIA ALE-1 4.00 23 111 4.83 2 ALEGRIA ALE-2 4.63 28 132 4.71 3 ALEGRIA ALE-5b 6.82 21 113 5.38 4 ALEGRIA ALE-10 4.00 19 81 4.26 5 ALEGRIA ALE-15 5.40 26 138 5.31 6 ALEGRIA ALE-15b 6.82 13 87 6.69 plot (INDAGUAFLASH[,3:6], col=3, pch=19)

  20. Representando 2 variables #EJEMPLO: DISPERSIÓN read.table ("C:/AMDDATOSR/INDAGUAFLASH.txt", header=T)-> INDAGUAFLASH attach (INDAGUAFLASH) head (INDAGUAFLASH) cuenca SITE IVAM NFAM IBMWP IASPT 1 ALEGRIA ALE-1 4.00 23 111 4.83 2 ALEGRIA ALE-2 4.63 28 132 4.71 3 ALEGRIA ALE-5b 6.82 21 113 5.38 4 ALEGRIA ALE-10 4.00 19 81 4.26 5 ALEGRIA ALE-15 5.40 26 138 5.31 6 ALEGRIA ALE-15b 6.82 13 87 6.69 plot (INDAGUAFLASH[,3:6], col=cuenca, pch=19)

  21. Representando 2 variables #EJEMPLO: SEN(X) #Preparamos los datos, un vector x (secuencia de 41 elementos de 1 a 2pi) #y otro vector y = seno(x) x <- seq ( from=1, to=2*pi, length=41 ) y <- sin(x) plot (x, y, col="red", cex=2) curve (sin, add=T, lwd=2)

  22. Representando 2 variables Ciclos de atributos de símbolos: 3 colores (col) y 3 tamaños (cex): color <- c("red", "blue", "green") plot (x, y, col=color, cex=1:3, lwd=4, ylim = c(-1,1.5)) lines (x,y, lwd=2)

  23. Representando 2 variables EJEMPLO GRAFICOS PERFILES PROFUNDIDAD:EMBALSE DE BÚBAL read.table("C:/AMDDATOSR/R perfiles embalses2009.txt", header=T)->perf2009 attach(perf2009) #Dividimos nuestra matriz por el factor código de embalse, COD, split (perf2009,COD)-> perf2009 attach(perf2009$BUB) head(perf2009$BUB) COD DEP COND DO Temp pH 126 BUB 0.0 147 10.37 19.40 8.34 127 BUB 1.0 146 10.66 18.59 8.39 128 BUB 2.0 146 10.44 18.44 8.42 129 BUB 2.9 146 10.51 18.27 8.44 130 BUB 4.0 146 10.57 18.18 8.47 131 BUB 5.0 141 11.25 17.48 8.44

  24. Representando 2 variables EJEMPLO GRAFICOS PERFILES PROFUNDIDAD:EMBALSE DE BÚBAL Ejemplo, perfil de temperatura: plot (Temp, DEP, type="o", col = "red", main= "Embalse de Búbal", cex.main=.8, pch = 20, cex = 1, ylab="profundidad (m)", xlab="temperarura (ºC)", font=1, cex.axis=.7, cex.lab=.8, lwd=.7, col.axis="black", ylim=c(53,0), mgp=c(1.5, .6, 0)) axis ( 3, cex.axis=.7, tck=-.03, mgp=c(1.5,.6,0)) #savePlot ("BUBtemp",type = "emf")

  25. Representando 2 variables EJEMPLO GRAFICOS PERFILES PROFUNDIDAD:EMBALSE DE BÚBAL Ejemplo, perfil de temperatura:

  26. Gráficos tridimensionales EJEMPLO: Visualizar un MDT # (3) Visualizing a simple DEM model z <- 2 * volcano x <- 10 * (1:nrow(z)) y <- 10 * (1:ncol(z)) persp (x, y, z, theta = 135, phi = 30, col = "green3", scale = FALSE, ltheta = -120, shade = 0.75, border = NA, box = FALSE)

  27. Gráficos tridimensionales EJEMPLO:

  28. Gráficos Multivariantes GRAFICOS DE ESTRELLAS (función star) Ejemplo, ÍNDICES BIÓTICOS EN LAS ESTACIONES Aguaflash: read.table ("C:/AMDDATOSR/INDAGUAFLASH.txt", header=T)-> INDAGUAFLASH attach(INDAGUAFLASH) stars (INDAGUAFLASH[,3:6], label=SITE ,cex=0.5, key.loc = c(18, 2.3))

  29. Gráficos Multivariantes GRAFICOS DE ESTRELLAS (función star) Ejemplo, GRUPOS FITOPLANCTON POR TIPOS EMBALSES DEL EBRO: read.table("C:/AMDDATOSR/fitotipos.txt", header=T)->fitotipos attach(fitotipos) stars (fitotipos, label=type ,cex=0.5, draw.segments=TRUE, key.loc=c(8, 2))

  30. Gráficos Multivariantes GRAFICOS DE ESTRELLAS (función star) Ejemplo, GRUPOS FITOPLANCTON POR TIPOS EMBALSES DEL EBRO: read.table("C:/AMDDATOSR/fitotipos.txt", header=T)->fitotipos attach(fitotipos)

  31. Gráficos de Regresión Modelos Lineales Generalizados (funciones: glm, abline, plot) Ejemplo: IASPT ~ IVAM (datos INDAGUAFLASH) glm (IASPT ~ IVAM)-> model plot (IASPT, IVAM, pch=19) abline (model, col=4, lwd=2) summary (model) Estimate Std. Error t value Pr(>|t|) (Intercept) 1.8479 0.5292 3.492 0.00119 ** IVAM 0.5800 0.1059 5.478 2.56e-06 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

  32. Gráficos de Regresión Modelos Lineales Generalizados (funciones: glm, abline, plot) Ejemplo: IASPT ~ IVAM (datos INDAGUAFLASH) glm (IASPT~IVAM)-> model plot (IASPT, IVAM, pch=19) abline (model, col=4, lwd=2) par(mfrow = c(2,2)) plot (model)

  33. Gráficos de Regresión Modelos Lineales (funciones: glm, lm, abline, plot). Intervalos de confianza. Ejemplo: IASPT ~ IVAM (datos INDAGUAFLASH) read.table ("C:/AMDDATOSR/embalses2009.txt", header=T)-> emb2009 attach (emb2009) lm (chla~pt)-> model plot (pt, chla, pch=19, xlab ="P total (µg/L) ", ylab= "Chla (µg/L)") abline (model, col=4, lwd=2) newx <- seq (min(pt), max(pt), 0.01) c <- predict (model, newdata=data.frame (pt=newx), interval="prediction") d <- predict (model, newdata=data.frame (pt=newx), interval="confidence") lines (newx, c[,2], lty=2, col="grey") lines (newx, c[,3], lty=2, col="grey") lines (newx, d[,2], lty=2, col= "red") lines (newx, d[,3], lty=2, col= "red") text (20,30,"Adjsted R-squared: 0.3819")

  34. Gráficos de Clasificación GRAFICOS DE CLUSTERS. DENDROGRAMAS (función agnes_paquete cluster) Ejemplo jerárquico: UPGMA (tipos embalses ~ fitoplancton) read.table("C:/AMDDATOSR/embalses2009.txt", header=T)-> emb2009; attach(emb2009) agnes ( log (emb2009 [, 43:51]+2), method="average") -> UPGMA plot (UPGMA, main="clasificación UPGMA embalses")

  35. Gráficos de Clasificación GRAFICOS DE CLUSTERS Ejemplo no jerárquico: K-Means (tipos embalses ~ fitoplancton) read.table ("E:/AMDDATOSR/embalses2009.txt", header=T)-> emb2009 attach(emb2009) emb2009 [,43:48] -> algasembalses library (stats) kmeans (algasembalses, 5, iter.max=100) -> kmemb2009 kmemb2009 K-means clustering with 5 clusters of sizes 1, 43, 2, 4, 7 Clustering vector: [1] 2 2 2 2 2 2 2 5 2 3 2 2 2 2 2 2 5 2 2 2 2 4 5 2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 [39] 2 4 4 2 2 5 2 2 5 5 2 5 2 2 2 4 2 3 2

  36. Gráficos de Clasificación GRAFICOS DE CLUSTERS Ejemplo no jerárquico: K-Means #Ahora los podemos representar en un plano de ordenación, ej. PCA library (ade4) dudi.pca( log (algasembalses+1), scannf=F, nf=2)-> pca pca data.frame nrow ncol content 1 $tab 57 6 modified array 2 $li 57 2 row coordinates 3 $l1 57 2 row normed scores 4 $co 6 2 column coordinates 5 $c1 6 2 column normed scores plot (pca$li, pch=19, col=kmemb2009$cluster, cex=1.25)

  37. Gráficos de Clasificación GRAFICOS DE CLUSTERS Ejemplo no jerárquico: K-Means as.factor (kmemb2009$cluster)-> kmgr s.class ( pca$li, kmgr, cstar=T, cellipse=T, cpoint=.75, clabel=.6)

  38. Gráficos de Ordenación BIPLOTS DE ORDENACIÓN (ej. CCA: Análisis Canónico de Correspondencias) función cca_paquete ADE4) data (rpjdl) millog <- log (rpjdl$mil + 1) iv1 <- cca (rpjdl$fau, millog, scan = FALSE) plot(iv1)

  39. Gráficos de Ordenación BIPLOTS DE ORDENACIÓN (ej. CCA: Análisis Canónico de Correspondencias) función cca_paquete ADE4)

  40. Gráficos de Ordenación BIPLOTS DE ORDENACIÓN (ej. CCA: Análisis Canónico de Correspondencias) función cca_paquete ADE4)

More Related