-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualizacion.Rmd
717 lines (428 loc) · 14.8 KB
/
visualizacion.Rmd
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
---
output:
xaringan::moon_reader:
lib_dir: libs
css: ["default", "default-fonts", "animate.css", "hygge"]
nature:
highlightStyle: github
highlightLines: true
highlightSpans: true
countIncrementalSlides: true
---
class: inverse, center
```{r , message=FALSE, warning=FALSE, include=FALSE}
library(fontawesome)
library(emo)
library(tidyverse)
library(datos)
library(knitr)
```
# `r fa("r-project", fill = 'steelblue')` para análisis de datos <br> <br>
## `Visualización` <br> <br> <br>
.large[Roxana N. Villafañe | LEMyP | <a href='http://twitter.com/data_datum'>`r fa("twitter", fill = 'steelblue')` @data_datum</a>] <br>
.large[Florencia D'Andrea | INTA-CONICET | <a href="http://twitter.com/cantoflor_87"> `r fa("twitter", fill = 'steelblue')` @cantoflor_87</a><br>]
<br><br><br><br><br> Slides disponibles en <https://flor14.github.io/visualizacion_2020/visualizacion#1> `r emo::ji("sparkles")`
<br> Página web del curso en <https://flor14.github.io/Curso_r_unne_2020/> `r emo::ji("star2")`
---
# Exploración de datos
```{r visu, echo=FALSE, fig.align = "center"}
knitr::include_graphics("visualizar.png")
```
.footnote[**Fuente**: https://es.r4ds.hadley.nz/explorar-introduccion.html]
---
class: center, middle
# Paquete `ggplot2`
```{r hex, echo=FALSE, out.width = "300px", fig.align = "center"}
knitr::include_graphics("hex.png")
```
---
# Guía Rápida
```{r cheat, echo=FALSE, out.width = "600px", fig.align = "center"}
knitr::include_graphics("cheatsheet.png")
```
.footnote[**Fuente**: RStudio Cheatsheet]
---
<img src="hex.png" width="10%" align="right" />
# Gramática de los gráficos
```{r ggplot, eval=FALSE}
ggplot(data = `<DATOS>`) +
`<GEOM_FUNCIÓN>`(mapping = aes(`<MAPEOS ESTÉTICOS>`))
```
```{r graficos, echo=FALSE, out.width = "600px", fig.align = "center"}
knitr::include_graphics("graficos.png")
```
.footnote[**Fuente**: RStudio Cheatsheet]
---
<img src="hex.png" width="10%" align="right" />
# Gramática de los gráficos
```{r ggplotplot, eval=FALSE}
ggplot(data = `<DATOS>`) +
`<GEOM_FUNCIÓN>`(mapping = aes(`<MAPEOS ESTÉTICOS>`))
```
```{r layers1, echo=FALSE, out.width = "600px", fig.align = "center"}
knitr::include_graphics("layers_1.png")
```
.footnote[**Fuente**: RStudio Cheatsheet]
---
<img src="hex.png" width="10%" align="right" />
# Datos
Dataset `millas` en español traducido por la comunidad **R4DS**
```{r eval=FALSE, include=FALSE}
#install.package("datos")
library(datos)
```
```{r r4dses, echo=FALSE, out.width = "200px", fig.align = "center"}
knitr::include_graphics("r4dses.png")
```
---
class: middle, inverse
# Función Geom 📈
---
<img src="hex.png" width="10%" align="right" />
# Función Geom
```{r ggplo44t, eval=FALSE}
ggplot(data = <DATOS>) +
`<GEOM_FUNCIÓN>`(mapping = aes(<MAPEOS>))
```
Las funciones `geom_*()` determinan la representación gráfica de los datos.
Cada función geom que uso forma una capa.
```{r geomexamples, echo=FALSE, out.width = "200px", fig.align = "center"}
knitr::include_graphics("geom_examples.png")
```
.footnote[**Fuente**: RStudio Cheatsheet]
---
class: middle, inverse
# Mapeos
---
<img src="hex.png" width="10%" align="right" />
# Mapeos
El mapeo entre las propiedades estéticas de tu gráfico y las variables de tu dataset te permite comunicar información sobre tus datos.
```{r ggplo444t, eval=FALSE}
library(tidyverse)
library(datos)
ggplot(data = <DATOS>) +
<GEOM_FUNCIÓN>(mapping = `aes(<MAPEOS>)`)
```
---
<img src="hex.png" width="10%" align="right" />
# Mapeos
Para mapear (o asignar) una estética a una variable, debes asociar el nombre de la estética al de la variable dentro de `aes()`.
```{r aes, echo=FALSE, out.width = "500px", fig.align = "center"}
knitr::include_graphics("aes.png")
```
---
<img src="hex.png" width="10%" align="right" />
Puedo incluir información de 3 variables
```{r ggplot2, echo=TRUE, fig.width=7, fig.height=5, fig.align = "center"}
library(tidyverse)
library(datos)
ggplot(data = millas) +
geom_point(mapping = aes(x = motor,
y = autopista,
color = clase))
```
---
class: middle, inverse, center
# 💡💻
# Demo #1
Generar un gráfico con `ggplot2`
Modificar las funciones `geom` y los mapeos
---
<img src="hex.png" width="10%" align="right" />
# Ejercicio
¿Por qué los puntos se ven rosados?
¿Qué pasa si sacas el argumento `color = "blue"` fuera de `aes()`?
```{r rere, echo=TRUE, fig.align= "center", fig.height=5, fig.width=7}
ggplot(data = millas) +
geom_point(mapping = aes(x = motor, y = autopista, color = "blue"))
```
---
class: middle
<img src="hex.png" width="10%" align="right" />
# Variable categórica
Una variable es categórica si solo puede tomar uno de un pequeño conjunto de valores -> **gráfico de barras** 📊
# Variable continua
Una variable es continua si puede tomar cualquiera de un conjunto infinito de valores -> **histograma** 📊
---
<img src="hex.png" width="10%" align="right" />
# Algunos ejemplos de gráficos
```{r gordi, echo=FALSE, out.width = "900px"}
knitr::include_graphics("cajas.png")
```
---
class: middle, inverse
# Gráfico de Barras
---
<img src="hex.png" width="10%" align="right" />
# `geom_bar()`
Grafico una variable
```{r bar, fig.width=7, fig.height=5, fig.align = "center"}
library(tidyverse)
ggplot(diamonds) +
geom_bar(aes(x = color))
```
---
<img src="hex.png" width="10%" align="right" />
# Argumentos `color` y `fill`
Agrego una segunda variable en forma de color
```{r fill, echo=FALSE, out.width = "600px", fig.align = "center"}
knitr::include_graphics("fill vs color.png")
```
.footnote[**Fuente**: RStudio Primers - Visualize data]
---
<img src="hex.png" width="10%" align="right" />
# Cuidado!
position = "fill"
position = "stack"
position = "dodge"
```{r pos_adj, echo=FALSE, out.width = "400px", fig.align = "center"}
knitr::include_graphics("position_adj.png")
```
Recomiendo: [RStudio Primers](https://rstudio.cloud/learn/primers/3.2)
---
class: middle, inverse, center
# 💡💻
# Demo #2
Genero un gráfico de barras.
¿Qué pasa si modifico el argumento `position`?
---
class: middle, inverse
# Histograma
---
<img src="hex.png" width="10%" align="right" />
# Histograma
Ajusta el ancho de las barras con el argumento `binwidth`
```{r histo, echo=FALSE, fig.width=7, fig.height=5, fig.align = "center"}
library(datos)
ggplot(data = diamantes) +
geom_histogram(mapping = aes(x = precio), binwidth = 5000)
```
---
class: middle, inverse
# Diagrama de caja
---
<img src="hex.png" width="10%" align="right" />
# Diagrama de caja
Los diagramas de caja representan gráficamente a los datos a través de sus cuartiles.
```{r box_adj, echo=FALSE, out.width = "400px", fig.align = "center"}
knitr::include_graphics("boxplot_imagen.png")
```
---
# Diagrama de caja
```{r caja, echo=TRUE, fig.align= "center", fig.height=5, fig.width=7}
library(datos)
ggplot(data = millas, mapping = aes(x = clase, y = autopista)) +
geom_boxplot()
```
---
<img src="hex.png" width="10%" align="right" />
# `geom_jitter()`
Puedo evaluar cuantos datos están representados
```{r cajajitter, echo=TRUE, fig.align= "center", fig.height=4, fig.width=6}
library(tidyverse)
library(datos)
ggplot(data = millas, mapping = aes(x = clase, y = autopista))+
geom_boxplot()+
geom_jitter()
```
---
<img src="hex.png" width="10%" align="right" />
# Giro el sistema de coordenadas
```{r graficos22, echo=FALSE, out.width = "300px", fig.align = "center"}
knitr::include_graphics("graficos.png")
```
```{r cajaj2, echo=TRUE, fig.align= "center", fig.height=3, fig.width=5}
library(tidyverse)
library(datos)
ggplot(data = millas, mapping = aes(x = clase, y = autopista)) +
geom_boxplot()+
geom_jitter()+
coord_flip()
```
---
class: middle, inverse
# Gráfico de puntos
# Gráfico de líneas
---
<img src="hex.png" width="10%" align="right" />
# Gráfico de puntos
Uso el argumento `color` para mapear una tercer variable
```{r puntos, echo=TRUE, fig.align= "center", fig.height=5, fig.width=7}
ggplot(data = millas) +
geom_point(mapping = aes(x = motor,
y = autopista,
color = clase))
```
---
<img src="hex.png" width="10%" align="right" />
# Gráfico de puntos
Si quiero observar tercer variable pero esta vez continua puedo usar otro argumento, como `size`
```{r size, echo=TRUE, fig.align= "center", fig.height=4, fig.width=6}
ggplot(data = millas)+
geom_point(mapping = aes(x = motor, y = autopista, size = cilindros))
```
---
<img src="hex.png" width="10%" align="right" />
# Gráfico de líneas
```{r lineas, echo=TRUE, fig.align= "center", fig.height=4, fig.width=6}
library(gapminder)
gapminder %>%
filter(country %in% c("Argentina","Brazil","Chile"))%>%
ggplot() +
geom_line(aes(x = year, y = pop, color = country),
size = 1.5)
```
---
class: middle, inverse, center
# 💡💻
# Demo #3
¿Cómo hago un gráfico que combina líneas y puntos?
Entiendo que los gráficos tienen capas
---
class: middle, inverse
# Heatmap
---
<img src="hex.png" width="10%" align="right" />
# `geom_tile()`
```{r tile, echo=TRUE, fig.align= "center", fig.height=4, fig.width=6}
ggplot(airquality, aes(x = Month, y = Day)) +
geom_tile(aes(fill=Temp))+
scale_fill_gradient(name = 'Temperature', low = 'white', high = 'red')+
labs(title="Temperature Readings by Date")
```
.footnote[http://analyticswithr.com/dataviz.html]
---
<img src="hex.png" width="10%" align="right" />
# Puede ser mas complejo
```{r heat, echo=FALSE, out.width="400px", fig.align = "center"}
knitr::include_graphics("superheatmap.png")
```
---
class: middle, inverse
# Escalas de colores 📊
---
# Tipos de escalas
Divergente, secuencial y cualitativa
```{r escalas, echo=FALSE, out.width = "500px", fig.align = "center"}
knitr::include_graphics("escalas.png")
```
---
# Un paquete con paletas de colores
¿Cuales son paletas divergentes/secuenciales/cualitativas?
Otra paleta es `viridis`
```{r heater, echo=TRUE, fig.align= "center", fig.height=6, fig.width=8}
library(RColorBrewer)
RColorBrewer::display.brewer.all()
```
---
```{r holala, echo=TRUE, fig.align= "center", fig.height=5, fig.width=7}
library(tidyverse)
library(datos)
dsamp <- sample_n(diamantes, size = 1000)
ggplot(dsamp,
aes(quilate, precio, colour = claridad))+
geom_point()+
scale_colour_brewer(palette = "Set1")
```
---
class: middle, inverse
# Facetas
Funciones `facet_grid` y `facet_wrap`
---
<img src="hex.png" width="10%" align="right" />
# `facet_wrap()`
Es más útil si tiene una sola variable con muchos niveles.
`nrow` y/o `ncol` son argumentos útiles.
```{r wrap, fig.width=6, fig.height=4, fig.align = "center"}
library(datos)
ggplot(diamantes) +
geom_bar(aes(x = color, fill = corte)) +
facet_wrap(~corte)
```
---
<img src="hex.png" width="10%" align="right" />
# `facet_grid()`
Es más útil cuando tiene dos variables discretas, y todas las combinaciones de las variables existen en los datos.
```{r grip, fig.width=6, fig.height=4, fig.align = "center"}
library(datos)
ggplot(diamantes) +
geom_bar(aes(x = color, fill = corte)) +
facet_grid(claridad~corte)
```
---
class: center, middle, inverse
# 💡💻
# Demo #4
Probemos todas las posibilidades de gráficos con `facet_wrap()` y `facet_grid()`
¿Qué pasa si empleo una variable continua para el facetado?
---
<img src="hex.png" width="10%" align="right" />
# Temas
Puedes encontrar más temas en el paquete [ggthemes](https://www.ggplot2-exts.org/ggthemes.html)
```{r themes1, echo=FALSE, fig.align="center", fig.height=5, fig.width=7, message=FALSE, warning=FALSE}
library(tidyverse)
library(gridExtra)
options(warn=-1)
p <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg,
colour = factor(gear))) + facet_wrap(~am) + labs(colour = "Gear")
p1 = p + theme_gray() + labs(title = "theme_gray")
p2 = p + theme_bw() + labs(title = "theme_bw")
p3 = p + theme_linedraw() + labs(title = "theme_linedraw")
p4 = p + theme_light() + labs(title = "theme_light")
p5 = p + theme_dark() + labs(title = "theme_dark")
p6 = p + theme_minimal() + labs(title = "theme_minimal")
p7 = p + theme_classic() + labs(title = "theme_classic")
p8 = p + theme_void() + labs(title = "theme_void")
grid.arrange(p1,p2,p3,p4)
```
.footnote[https://garthtarr.github.io/meatR/ggplot_extensions.html]
---
<img src="hex.png" width="10%" align="right" />
# Temas
```{r themes2, echo=FALSE, fig.align="center", fig.height=5, fig.width=7, message=FALSE, warning=FALSE}
library(tidyverse)
library(gridExtra)
options(warn=-1)
p <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg,
colour = factor(gear))) + facet_wrap(~am) + labs(colour = "Gear")
p1 = p + theme_gray() + labs(title = "theme_gray")
p2 = p + theme_bw() + labs(title = "theme_bw")
p3 = p + theme_linedraw() + labs(title = "theme_linedraw")
p4 = p + theme_light() + labs(title = "theme_light")
p5 = p + theme_dark() + labs(title = "theme_dark")
p6 = p + theme_minimal() + labs(title = "theme_minimal")
p7 = p + theme_classic() + labs(title = "theme_classic")
p8 = p + theme_void() + labs(title = "theme_void")
grid.arrange(p5,p6,p7,p8)
```
.footnote[https://garthtarr.github.io/meatR/ggplot_extensions.html]
---
<img src="hex.png" width="10%" align="right" />
# Ejes
## Cambio de nombre a los ejes
```{r ejes, echo=FALSE, fig.align = "center", fig.height=5, fig.width=7, message=FALSE, warning=FALSE}
ggplot(millas, aes(motor, autopista)) +
geom_point(aes(colour = clase)) +
geom_smooth(se = FALSE) +
labs(
x = "Desplazamiento del motor (L)",
y = "Economia de combustible de carretera (millas)",
colour = "Tipo de automóvil",
title = "Mi grafico"
)
```
---
class: center, middle, inverse
# Links
[ggplot2 Book](https://ggplot2-book.org/)
[R4DS español](https://es.r4ds.hadley.nz/)
[Rcookbook](http://www.cookbook-r.com/)
[Fundamentals of Data Visualization](https://serialmentor.com/dataviz/index.html)
[Geocomputation with R](https://geocompr.robinlovelace.net/index.html)
---
background-image: url(textura-fondo.png)
background-size: cover
class: center, middle, inverse
# `r emo::ji("raising_hand")` ¿Preguntas?
---
# Práctica