gráficos en r seminario ceh-cedex 21-22 febrero, 2011

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

Upload: ibbie-pecha

Post on 16-Feb-2015

6 views

Category:

Documents


0 download

TRANSCRIPT

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

Gráficos en R

Seminario CEH-CEDEX21-22 Febrero, 2011

Page 2: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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)

¿Porqué los gráficos?

Page 3: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

¿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

Page 4: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

¿Qué hay que pedir a un gráfico?

Entendibilidad1. ¿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?

Claridad1. ¿Son los elementos del gráfico claramente distinguibles?2. ¿Son los elementos más importantes del gráfico visualmente prominentes?

Consistencia1. ¿Son los elementos de los gráficos consistentes en gráficos anteriores?2. ¿Hay nuevos elementos que requieren una descripción adicional?

Page 5: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Eficiencia1. ¿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?

Necesidad1. ¿Es el gráfico útil para representar estos datos?2. ¿Es cada elemento en el gráfico necesario?

Confiabilidad1. ¿Están los datos adecuadamente colocados en la región de datos?2. ¿Están los datos representados adecuadamente por la escala?

¿Qué hay que pedir a un gráfico?

Page 6: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

• 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...)

Gráficos distorsionados

Page 7: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos distorsionados

Page 8: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos distorsionados

Page 9: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos distorsionados

¡¡cuidado con los gráficos que se nos presentan!!!

Leer bien las escalas y las variables presentadas.

Page 10: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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 (?!?!?!?)

Hombres

Mujeres

Page 11: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos circulares (pie charts)

read.table("C:/AMDDATOSR/embalses2009.txt", header=T)-> emb2009; attach(emb2009)

table (tipo) = tipotablepie (tipotable, col=c(1:8), main= " Tipos Embalses")

1

7

9

10

11

12

13

Tipos Embalses

Page 12: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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)

0 2 4 6 8 10 12 14

05

00

10

00

15

00

Page 13: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Boxplot o Caja de Tukey

read.table("C:/AMDDATOSR/INDAGUAFLASH.txt", header=T)-> INDAGUAFLASHattach(INDAGUAFLASH)

boxplot ( IBMWP ~ cuenca, col=c("yellow","blue" , "green","red" ))

ALEGRIA ENXOE FLUMEN SAVE

50

10

01

50

20

0

Page 14: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Boxplots o Cajas de TukeyPodemos 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)

ALEGRIA ENXOE FLUMEN SAVE

50

10

01

50

20

0

IBMWP por cuencas

cuenca

IBM

WP

Page 15: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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)

Histogram of x

x

De

nsi

ty

0 5 10 15

0.0

00

.05

0.1

00

.15

0.2

0

Page 16: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Histogramas

#Comparemos con la funcion de probabilidad Chi2

curve (dchisq (x, df = 4), col = 2, lty = 2, lwd = 2, add = TRUE)

Histogram of x

x

De

nsi

ty

0 5 10 15

0.0

00

.05

0.1

00

.15

0.2

0

Page 17: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Histogramas

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)))))

histograma de superficie de embalses

superficie (Ha)

em

ba

lse

s

0 1000 3000 5000

01

02

03

04

0

read.table("C:/AMDDATOSR/embalses2008.txt", header=T)-> emb2008; attach(emb2008)

Page 18: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Diagramas de densidad de Kerneldensity (IBMWP) -> densibmwp

plot (densibmwp, main= "Densidad índice IBMWP", xlab= "IBMWP", ylab= " densidad",xlim=c(0,300)) polygon (densibmwp, col=1)

0 50 100 150 200 250 300

0.0

00

0.0

04

0.0

08

Densidad índice IBMWP

IBMWP

de

nsi

da

d

Page 19: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Representando 2 variables

#EJEMPLO: DISPERSIÓN

read.table ("C:/AMDDATOSR/INDAGUAFLASH.txt", header=T)-> INDAGUAFLASHattach(INDAGUAFLASH)

head (INDAGUAFLASH)

cuenca SITE IVAM NFAM IBMWP IASPT1 ALEGRIA ALE-1 4.00 23 111 4.832 ALEGRIA ALE-2 4.63 28 132 4.713 ALEGRIA ALE-5b 6.82 21 113 5.384 ALEGRIA ALE-10 4.00 19 81 4.265 ALEGRIA ALE-15 5.40 26 138 5.316 ALEGRIA ALE-15b 6.82 13 87 6.69

plot (INDAGUAFLASH[,3:6], col=3, pch=19)

IVAM

5 10 20 30 0 10 20 30 40

05

1020

30

510

2030

NFAM

IBMWP

5010

015

020

0

0 5 10 20 30

010

2030

40

50 100 150 200

IASPT

Page 20: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Representando 2 variables

#EJEMPLO: DISPERSIÓN

read.table ("C:/AMDDATOSR/INDAGUAFLASH.txt", header=T)-> INDAGUAFLASHattach (INDAGUAFLASH)

head (INDAGUAFLASH)

cuenca SITE IVAM NFAM IBMWP IASPT1 ALEGRIA ALE-1 4.00 23 111 4.832 ALEGRIA ALE-2 4.63 28 132 4.713 ALEGRIA ALE-5b 6.82 21 113 5.384 ALEGRIA ALE-10 4.00 19 81 4.265 ALEGRIA ALE-15 5.40 26 138 5.316 ALEGRIA ALE-15b 6.82 13 87 6.69

plot (INDAGUAFLASH[,3:6], col=cuenca,pch=19)

IVAM

5 15 30 3 4 5 6

24

6

515

30

NFAM

IBMWP

5015

0

2 4 6

34

56

50 150

IASPT

Page 21: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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)

1 2 3 4 5 6

-1.0

-0.5

0.0

0.5

1.0

x

y

Page 22: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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)

1 2 3 4 5 6

-1.0

-0.5

0.0

0.5

1.0

1.5

x

y

Page 23: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Representando 2 variablesEJEMPLO GRAFICOS PERFILES PROFUNDIDAD:EMBALSE DE BÚBAL

read.table("C:/AMDDATOSR/R perfiles embalses2009.txt", header=T)->perf2009attach(perf2009)

#Dividimos nuestra matriz por el factor código de embalse, COD, split (perf2009,COD)-> perf2009attach(perf2009$BUB)

head(perf2009$BUB)COD DEP COND DO Temp pH126 BUB 0.0 147 10.37 19.40 8.34127 BUB 1.0 146 10.66 18.59 8.39128 BUB 2.0 146 10.44 18.44 8.42129 BUB 2.9 146 10.51 18.27 8.44130 BUB 4.0 146 10.57 18.18 8.47131 BUB 5.0 141 11.25 17.48 8.44

Page 24: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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")

Page 25: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Representando 2 variables

8 10 12 14 16 18

5040

3020

100

Embalse de Búbal

temperarura (ºC)

prof

undi

dad

(m)

8 10 12 14 16 18

EJEMPLO GRAFICOS PERFILES PROFUNDIDAD:EMBALSE DE BÚBAL

Ejemplo, perfil de temperatura:

Page 26: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos tridimensionalesEJEMPLO: Visualizar un MDT# (3) Visualizing a simple DEM modelz <- 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)

Page 27: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos tridimensionalesEJEMPLO:

X

-10-5

05

10

Y

-10

-5

0

510

Sinc( r )

-202468

Page 28: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos MultivariantesGRAFICOS DE ESTRELLAS (función star)

Ejemplo, ÍNDICES BIÓTICOS EN LAS ESTACIONES Aguaflash:read.table ("C:/AMDDATOSR/INDAGUAFLASH.txt", header=T)-> INDAGUAFLASHattach(INDAGUAFLASH)

stars (INDAGUAFLASH[,3:6], label=SITE ,cex=0.5, key.loc = c(18, 2.3))

ALE-1 ALE-2 ALE-5b ALE-10 ALE-15 ALE-15b ALE-16b

ALE-17 ALE-20 ALE-31 ENXOE1_1 ENXOE1_2 ENXOE2_1 ENXOE2_2

ENXOE3 ENXOE6_3 ENXOE6_3b ENXOE7_1 ENXOE7_2 ENXOE7_3 ENXOE7_4

ENXOE7_5 FLU-1 FLU-2 FLU-9 FLU-4 FLU-4b FLU-7

FLU-6 FLU-8 FLU-10 FLU-5 FLU-3 SAVE-1 SAVE-2

SAVE-3 SAVE-4 SAVE-6 SAVE-7 SAVE-8 SAVE-9 SAVE-10

SAVE-11 SAVE-12

IVAM

NFAM

IBMWP

IASPT

Page 29: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

GRAFICOS DE ESTRELLAS (función star)

Ejemplo, GRUPOS FITOPLANCTON POR TIPOS EMBALSES DEL EBRO:

stars (fitotipos, label=type ,cex=0.5, draw.segments=TRUE, key.loc=c(8, 2))

read.table("C:/AMDDATOSR/fitotipos.txt", header=T)->fitotiposattach(fitotipos)

Gráficos Multivariantes

Page 30: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

GRAFICOS DE ESTRELLAS (función star)

Ejemplo, GRUPOS FITOPLANCTON POR TIPOS EMBALSES DEL EBRO:

read.table("C:/AMDDATOSR/fitotipos.txt", header=T)->fitotiposattach(fitotipos)

1 7 9

10 11 12

13

Baci

ChloroChryso

Conju

Crypto

Cyano Dino

Eugle

Gráficos Multivariantes

Page 31: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Modelos Lineales Generalizados (funciones: glm, abline, plot) Ejemplo: IASPT ~ IVAM (datos INDAGUAFLASH)

Gráficos de Regresión

glm (IASPT ~ IVAM)-> modelplot (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

3 4 5 62

34

56

7

IASPT

IVA

M

Page 32: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Modelos Lineales Generalizados (funciones: glm, abline, plot)Ejemplo: IASPT ~ IVAM (datos INDAGUAFLASH)

Gráficos de Regresión

glm (IASPT~IVAM)-> modelplot (IASPT, IVAM, pch=19)abline (model, col=4, lwd=2)

par(mfrow = c(2,2))plot (model)

3.0 3.5 4.0 4.5 5.0 5.5

-2-1

01

2

Predicted values

Res

idua

ls

Residuals vs Fitted

3118

42

-2 -1 0 1 2

-2-1

01

2

Theoretical Quantiles

Std

. de

vian

ce r

esid

.

Normal Q-Q

3118

42

3.0 3.5 4.0 4.5 5.0 5.5

0.0

0.5

1.0

1.5

Predicted values

Std

. de

vian

ce r

esid

.

Scale-Location31

1842

0.00 0.05 0.10 0.15

-2-1

01

2

LeverageS

td.

Pea

rson

res

id.

Cook's distance 0.5

0.5

Residuals vs Leverage

11

31

25

Page 33: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Modelos Lineales (funciones: glm, lm, abline, plot). Intervalos de confianza.Ejemplo: IASPT ~ IVAM (datos INDAGUAFLASH)

read.table ("C:/AMDDATOSR/embalses2009.txt", header=T)-> emb2009attach (emb2009)

Gráficos de Regresión

lm (chla~pt)-> modelplot (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")

0 20 40 60 800

10

20

30

40

P total (µg/L)

Ch

la (

µg

/L)

Adjsted R-squared: 0.3819

Page 34: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

GRAFICOS DE CLUSTERS. DENDROGRAMAS (función agnes_paquete cluster)

Ejemplo jerárquico: UPGMA (tipos embalses ~ fitoplancton)

Gráficos de Clasificación

read.table("C:/AMDDATOSR/embalses2009.txt", header=T)-> emb2009; attach(emb2009)

agnes ( log (emb2009 [, 43:51]+2), method="average") -> UPGMAplot (UPGMA, main="clasificación UPGMA embalses")

14

51

11

22 7

48

20

22

23

44 24

25

50 2

84

63

49

53

24

43

18

57

29

21

39 5

2 62

73

31

52

64

25

58

93

81

74

71

33

4 37

53

31

36

14

19

16

35

51

10

30

54

40

41

56

02

46

8

clasificación UPGMA embalses

Agglomerative Coefficient = 0.72log(emb2009[, 43:51] + 2)

He

igh

t

Page 35: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

GRAFICOS DE CLUSTERSEjemplo no jerárquico: K-Means (tipos embalses ~ fitoplancton)

Gráficos de Clasificación

read.table ("E:/AMDDATOSR/embalses2009.txt", header=T)-> emb2009attach(emb2009)emb2009 [,43:48] -> algasembalses

library (stats)kmeans (algasembalses, 5, iter.max=100) -> kmemb2009kmemb2009

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

Page 36: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos de Clasificación

#Ahora los podemos representar en un plano de ordenación, ej. PCA

library (ade4)dudi.pca( log (algasembalses+1), scannf=F, nf=2)-> pcapca

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)

GRAFICOS DE CLUSTERSEjemplo no jerárquico: K-Means

Page 37: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

Gráficos de Clasificación

GRAFICOS DE CLUSTERSEjemplo no jerárquico: K-Meansas.factor (kmemb2009$cluster)-> kmgrs.class ( pca$li, kmgr, cstar=T, cellipse=T, cpoint=.75, clabel=.6)

d = 2

1

2

3

4

5

Page 38: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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

Gráficos de Ordenación

data (rpjdl) millog <- log (rpjdl$mil + 1)iv1 <- cca (rpjdl$fau, millog, scan = FALSE) plot(iv1)

Page 39: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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

Gráficos de Ordenación

d = 0.2

Loadings

d = 0.2

(Intercept)

ROCH

C.25

C.50

C1 C2

C4

C8

C16

Loadings

d = 0.5

Correlation

d = 0.5

(Intercept)

ROCH

C.25

C.50

C1

C2

C4 C8 C16

Correlation

Axis1

Axis2

Axis3 Axis4 Axis5 Axis6

Axis7

Axis8

Inertia axes

d = 0.5

Scores and predictions

1 2

3

4

5

6

7 8

9 10

11

12 13

14 15 16

17

18

19 20

21 22

23

24 25

26 27 28

29

30

31

32

33

34

35

36 37 38

39

40

41 42 43 44

45 46

47

48

49

50

51 52

53 54 55

56 57 58

59 60 61

62

63

64

65 66

67 68 69

70

71 72

73

74 75

76

77 78 79 80

81

82

83

84 85

86 87

88 89

90

91

92 93

94

95

96 97

98 99

100 101

102 103

104 105 106

107

108

109 110

111 112 113 114

115

116

117 118 119

120 121 122 123 124 125 126

127 128

129 130

131

132

133

134

135 136 137

138 139

140

141 142

143

144 145

146 147 148 149

150 151

152

153

154

155

156 157 158 159

160 161 162 163 164

165 166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

182

d = 0.5

Species

AR CP

ST CC

UE PV

JT

GT

LA OO PP

GG

PM PC PR AA SE CB

TT

TM

MS

MO

OH

OL

SO LM

ER

HP

SH

SB SA

SC

SM

SN

SP

SU

PB Rl

PO

AC

LS CH

CA CN SS

FC MC

EC EH

El

PD

Eigenvalues

Page 40: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011

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

Gráficos de Ordenación

ROCH

C.25

C.50

C1

C2

C4 C8

d = 2

AR

CP ST CC

UE

PV JT

GT LA

OO

PP

GG PM PC

PR AA SE CB TT

TM

MS

MO OH OL

SO

LM

ER

HP

SH

SB

SA

SC

SM

SN

SP

SU

PB Rl

PO

AC

LS CH

CA

CN

SS

FC

MC

EC

EH

El

PD

Page 41: Gráficos en R Seminario CEH-CEDEX 21-22 Febrero, 2011