background-color: #272822 <br> <br> <br> <br> <br> <br> <h1 style='color:white'> <center> R para contextos humanitarios de emergencia</center></h1> ## <center><font style='color:#E495A5'>V</font><font style='color:#D89F7F'>i</font><font style='color:#BDAB66'>s</font><font style='color:#96B56C'>u</font><font style='color:#65BC8C'>a</font><font style='color:#39BEB1'>l</font><font style='color:#55B8D0'>i</font><font style='color:#91ACE1'>z</font><font style='color:#C29DDE'>a</font><font style='color:#DE94C8'>c</font><font style='color:#E495A5'>i</font><font style='color:#D89F7F'>ó</font><font style='color:#BDAB66'>n</font> <font style='color:#96B56C'>d</font><font style='color:#65BC8C'>e</font> <font style='color:#39BEB1'>d</font><font style='color:#55B8D0'>a</font><font style='color:#91ACE1'>t</font><font style='color:#C29DDE'>o</font><font style='color:#DE94C8'>s</font> <font style='color:#E495A5'>I</font></center> ### <center><font style='color:#E495A5'>V</font><font style='color:#D89F7F'>i</font><font style='color:#BDAB66'>o</font><font style='color:#96B56C'>l</font><font style='color:#65BC8C'>e</font><font style='color:#39BEB1'>t</font><font style='color:#55B8D0'>a</font> <font style='color:#91ACE1'>R</font><font style='color:#C29DDE'>o</font><font style='color:#DE94C8'>i</font><font style='color:#E495A5'>z</font><font style='color:#D89F7F'>m</font><font style='color:#BDAB66'>a</font><font style='color:#96B56C'>n</font></center> --- background-color: #272822 <br> <br> <br> <br> <br> <br> <h1 style='color:white'> <center> Abrir el archivo 04-EJ-visualizacion.Rmd</center></h1> ## <center><font style='color:#E495A5'>P</font><font style='color:#D89F7F'>a</font><font style='color:#BDAB66'>r</font><font style='color:#96B56C'>a</font> <font style='color:#65BC8C'>i</font><font style='color:#39BEB1'>r</font> <font style='color:#55B8D0'>h</font><font style='color:#91ACE1'>a</font><font style='color:#C29DDE'>c</font><font style='color:#DE94C8'>i</font><font style='color:#E495A5'>e</font><font style='color:#D89F7F'>n</font><font style='color:#BDAB66'>d</font><font style='color:#96B56C'>o</font> <font style='color:#65BC8C'>l</font><font style='color:#39BEB1'>o</font><font style='color:#55B8D0'>s</font> <font style='color:#91ACE1'>E</font><font style='color:#C29DDE'>J</font></center> --- <div class="my-header"></div> ## Visualización de datos <center><img src="img/ggplot2_obra_maestra.png" width="700"></center> <p style="color: gray; font-size:15px"> Ilustración de Allison Horst. </p> --- <div class="my-header"></div> ## Ejemplos: <img src="04-SLD-visualizacionI_files/figure-html/unnamed-chunk-3-1.png" width="648" /> --- <div class="my-header"></div> ## Ejemplos: <img src="04-SLD-visualizacionI_files/figure-html/unnamed-chunk-4-1.png" width="648" /> --- <div class="my-header"></div> ## Ejemplos: <center><img src="img/mapa1_ejemplo.png" height="500"></center> <p style="color: gray; font-size:15px"> Visualización de Cédric Scherer. </p> --- <div class="my-header"></div> ## Ejemplos: <center><img src="img/ggplot2-carbonprint.png" height="500"></center> <p style="color: gray; font-size:15px"> Visualización de Cédric Scherer. </p> --- <div class="my-header"></div> ## Los datos: campamentos en Haití Ahora vamos ver algunos ejemplos con un dataset de los campamentos de Haití ```r str(haiti) ``` ``` ## tibble [23 x 18] (S3: tbl_df/tbl/data.frame) ## $ SSID : chr [1:23] "121_03_326" "116_03_001" "114_05_353" "118_03_027" ... ## $ Commune : chr [1:23] "LEOGANE" "GRESSIER" "PETION-VILLE" "TABARRE" ... ## $ CampName : chr [1:23] "MOPAL" "Teren de la Kolin" "Tabarre ISA" "Centre Refugies Hatiens" ... ## $ Latitude : num [1:23] 18.5 18.5 18.5 18.6 18.6 ... ## $ Longitude : num [1:23] -72.6 -72.6 -72.2 -72.3 -72.2 ... ## $ Households : num [1:23] 6 139 546 260 11 458 328 417 900 67 ... ## $ Individuals : num [1:23] 28 604 2894 1237 45 ... ## $ #Shelters : num [1:23] 6 139 553 224 28 584 328 445 898 69 ... ## $ Percent_TShelter : num [1:23] 0 0 100 100 100 0 0 70 100 100 ... ## $ CMA Presence : chr [1:23] "No" "No" "No" "No" ... ## $ Committee Presence : chr [1:23] "Yes" "Yes" "Yes" "Yes" ... ## $ Presence of Toilets : chr [1:23] "Yes Toilets" "Yes Toilets" "No Toilets" "Yes Toilets" ... ## $ Water Provision : chr [1:23] "No Water" "No Water" "No Water" "Yes Water" ... ## $ Committee for Water : chr [1:23] "NO" "NO" "NO" "NO" ... ## $ Presence of Bathing : chr [1:23] "No Bathing" "No Bathing" "No Bathing" "No Bathing" ... ## $ Waste Management : chr [1:23] "No Waste" "No Waste" "No Waste" "No Waste" ... ## $ Committee for Garbage : chr [1:23] "NO" "NO" "NO" "NO" ... ## $ Other Organization provide Services: chr [1:23] "No Other Service" "No Other Service" "No Other Service" "No Other Service" ... ``` --- <div class="my-header"></div> ## Los datos: campamentos en Haití Variables: - Comuna - Nombre del campamento - Latitud - Longitud - Cantidad de Viviendas - Cantidad de Individuos - Provisión de Agua - Presencia de Sanitarios - etc. Que relación pensamos que debería haber entre Cantidad de Viviendas y Cantidad de Individuos? --- <div class="my-header"></div> ## Código `ggplot2` ![](img/templateggplot21.png) **Plantilla para cualquier gráfico:** ![](img/templateggplot22.png) --- <div class="my-header"></div> ## Algunas propiedades estéticas posibles - Ejes (x, y,...) - color (color de borde o de cosas sin relleno como punto o línea) - fill (color de relleno) - shape (por ejemplo para dispersión, círculo, triángulo, equis) - size (tamaño) - alpha (transparencia) ## Según el tipo de variable y de gráfico - numérica continua - categórica - texto --- <div class="my-header"></div> ## Color Supongamos que queremos distinguir además cuales de estos campamentos tienen Provisión de Agua .pull-left[ <center><b>Espacio Visual</b></center> <center>Color</center> <br> <center> <p style="color:#F8766D"> rojo </p> </center> <center> <p style="color:#00BFC4"> azul</p> </center> ] .pull-right[ <center><b>Espacio de los datos</b></center> <center>Provision de Agua</center> <br> <center> <p>No</p> </center> <center> <p>Yes</p> </center> ] --- <div class="my-header"></div> ## Mapear provisión de agua ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals, color = `Water Provision`)) ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-7-1.png)<!-- --> La leyenda se agrega automáticamente --- <div class="my-header"></div> ## Mapear provisión de agua ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals, shape = `Water Provision`)) ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-8-1.png)<!-- --> La leyenda se agrega automáticamente --- <div class="my-header"></div> ## Mapear provisión de agua ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals, size = `Water Provision`)) ``` ``` ## Warning: Using size for a discrete variable is not advised. ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-9-1.png)<!-- --> La leyenda se agrega automáticamente --- <div class="my-header"></div> ## Cómo hacer este gráfico? ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-10-1.png)<!-- --> --- <div class="my-header"></div> **Encuesta:** [PollEv.com/violetaroizm482](PollEv.com/violetaroizm482) a) ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals), color = "blue") ``` b) ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals), color = "red") ``` c) ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals, color = "blue") ``` d) ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals, color = "red")) ``` --- <div class="my-header"></div> ## Como hacer este gráfico? ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals, color = "blue")) ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-15-1.png)<!-- --> --- <div class="my-header"></div> ## Como hacer este gráfico? Si quiero indicar una característica estética NO linkeada a variable, entonces lo indico AFUERA del aes() ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals), color = "blue") ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-16-1.png)<!-- --> --- <div class="my-header"></div> ## Que tienen de distinto estos dos gráficos? .pull-left[ ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-17-1.png)<!-- --> ] .pull-right[ ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-18-1.png)<!-- --> ] --- <div class="my-header"></div> ## Que tienen de distinto estos dos gráficos? .pull-left[ ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-19-1.png)<!-- --> ] .pull-right[ ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-20-1.png)<!-- --> ] Mismos datos, mismo mapeo de aesthetics pero distinto geom `geom_point` y `geom_smooth` --- <div class="my-header"></div> # Tu turno 1 Reproducir este histograma de la distribución de la cantidad de personas que viven en el hogar del entrevistado (variable `b10_tamanio_hogar`) con la ayuda de la guía rápida de `ggplot2`. Usa `geom_histogram`. Ayuda: no utilizar la variable `y` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-22-1.png)<!-- --> --- <div class="my-header"></div> # Tu turno 2 Reproducir este gráfico de barras que grafica la cantidad de encuestados por cada departamento. Utiliza la ayuda de la guía rápida de `ggplot2`. Usa `geom_bar`. Ayuda: no utilizar la variable `y` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-23-1.png)<!-- --> --- <div class="my-header"></div> ## Gráficos de barras ```r ggplot(data_4ta_Ronda) + geom_bar(aes(b6_departamento, color = b6_departamento)) ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-24-1.png)<!-- --> --- <div class="my-header"></div> ## Gráficos de barras ```r ggplot(data_4ta_Ronda) + geom_bar(aes(b6_departamento, fill = b6_departamento)) ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-25-1.png)<!-- --> --- <div class="my-header"></div> # Gráficos de barras ```r ggplot(data_4ta_Ronda) + geom_bar(aes(b6_departamento, fill = b6_departamento)) + coord_flip() ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-26-1.png)<!-- --> --- <div class="my-header"></div> # Gráficos de barras ```r ggplot(data_4ta_Ronda) + geom_bar(aes(b6_departamento, fill = b6_departamento)) + labs(y = "cantidad", x = "") + coord_flip() + theme_minimal() + theme(legend.position = "none") ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-27-1.png)<!-- --> --- <div class="my-header"></div> # Tu turno 3 Predice la salida del siguiente código ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals)) + geom_smooth(mapping = aes(x = Households, y = Individuals)) ``` --- <div class="my-header"></div> ## Varias capas Cada nuevo `geom_...` agrega una capa ```r ggplot(data = haiti) + geom_point(mapping = aes(x = Households, y = Individuals)) + geom_smooth(mapping = aes(x = Households, y = Individuals)) ``` ``` ## `geom_smooth()` using method = 'loess' and formula 'y ~ x' ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-29-1.png)<!-- --> --- <div class="my-header"></div> ## Mapeos globales vs mapeos locales Podemos mapear características estéticas para todos los geoms así ```r ggplot(data = haiti, mapping = aes(x = Households, y = Individuals)) + geom_point() + geom_smooth() ``` ``` ## `geom_smooth()` using method = 'loess' and formula 'y ~ x' ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-30-1.png)<!-- --> --- <div class="my-header"></div> ## Mapeos globales vs mapeos locales Podemos agregar mapeos locales así ```r ggplot(data = haiti, mapping = aes(x = Households, y = Individuals)) + geom_point(mapping = aes(color = `Water Provision`)) + geom_smooth() ``` ``` ## `geom_smooth()` using method = 'loess' and formula 'y ~ x' ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-31-1.png)<!-- --> --- <div class="my-header"></div> ## Mapeos globales vs mapeos locales Que sucede aquí? ```r ggplot(data = haiti, mapping = aes(x = Households, y = Individuals, color = `Water Provision`)) + geom_point() + geom_smooth() ``` ``` ## Warning in max(ids, na.rm = TRUE): no non-missing arguments to max; returning - ## Inf ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-32-1.png)<!-- --> --- <div class="my-header"></div> ## Mapeos globales vs mapeos locales Incluso, podemos hacer mapeos locales de datos: ```r ggplot(data = haiti, mapping = aes(x = Households, y = Individuals)) + geom_point(aes(color = `Water Provision`)) + geom_smooth(data = filter(haiti, Households < 500)) ``` ``` ## `geom_smooth()` using method = 'loess' and formula 'y ~ x' ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-33-1.png)<!-- --> --- <div class="my-header"></div> ## Salvar gráficos La función `ggsave` salva el último gráfico generado Debemos especificar el nombre del archivo En general indicaremos un path relativo ```r ggsave("data/my-plot.pdf") ggsave("data/my-plot.png") ``` El tamaño default en general no es muy bueno. Podemos indicar las dimensiones ```r ggsave("data/my-plot.pdf", width = 6, height = 6) ``` **Tu turno 4:** Salva tu último gráfico en la carpeta img de tu proyecto Si por algún motivo no estás en un proyecto, vuelve al proyecto del curso --- <div class="my-header"></div> ## Más gráficos Volvamos a la tabla de decisiones de pedidos de asilos en Colombia ```r decisiones ``` ``` ## # A tibble: 133 x 16 ## Anio `Codigo Pais Or~ `Codigo Pais As~ `Nombre Pais de~ `Nombre Pais As~ ## <dbl> <chr> <chr> <chr> <chr> ## 1 2002 CUB COL Cuba Colombia ## 2 2002 IRQ COL Iraq Colombia ## 3 2003 IRN COL Iran (Islamic R~ Colombia ## 4 2003 IRN COL Iran (Islamic R~ Colombia ## 5 2003 VEN COL Venezuela (Boli~ Colombia ## 6 2004 CUB COL Cuba Colombia ## 7 2004 PER COL Peru Colombia ## 8 2004 UZB COL Uzbekistan Colombia ## 9 2005 CUB COL Cuba Colombia ## 10 2005 CUB COL Cuba Colombia ## # ... with 123 more rows, and 11 more variables: `Tipo de procedimiento` <chr>, ## # `Nombre del Procedimiento` <chr>, `Codigo de Tipo de Decision` <chr>, `Tipo ## # de Datos de Decision` <chr>, `Datos de Decision` <chr>, `Promedio de ## # Personas de decision por Caso` <dbl>, Reconocidas <dbl>, `Proteccion ## # Complementaria` <dbl>, `Cerradas de otra forma` <dbl>, Rechazadas <dbl>, ## # total <dbl> ``` --- <div class="my-header"></div> ## Series de tiempo Podemos graficar una variable a lo largo del tiempo para detectar tendencias, eventos y sus consecuencias <center><img src="img/series_tiempo.png" height="460"></center> --- ## Series de tiempo Podemos graficar una variable a lo largo del tiempo para detectar tendencias, eventos y sus consecuencias <center><img src="img/grafico_autoras_mujeres.jfif" height="460"></center> --- <div class="my-header"></div> ## Series de tiempo Podemos graficar una variable a lo largo del tiempo con una línea Utilizamos `geom_line` ```r decisiones %>% filter(`Codigo Pais Origen` == "VEN") %>% ggplot() + geom_line(aes(Anio, total)) ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-38-1.png)<!-- --> --- <div class="my-header"></div> ## Tu turno 5: Modifica el gráfico anterior para que la línea sea roja y cambia su grosor ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-39-1.png)<!-- --> --- <div class="my-header"></div> ## Gráficos por paneles A veces es más claro si tenemos varios paneles, uno para cada valor de una variable categórica/discreta ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-40-1.png)<!-- --> --- <div class="my-header"></div> ## Gráficos por paneles Para eso agregamos una capa llamada `facet_*` - `facet_wrap` - `facet_grid` Por default las escalas son las mismas En caso de que tenga sentido cambiarlas podemos agregar `scales="free"` como opción --- <div class="my-header"></div> ## Gráficos por paneles Podemos obtener el gráfico anterior de la siguiente forma: ```r decisiones %>% filter(`Codigo Pais Origen` %in% c("VEN", "ECU", "CUB")) %>% ggplot() + geom_line(aes(Anio, total, color = `Codigo Pais Origen`)) + facet_wrap(~ `Codigo Pais Origen`,) ``` puedes indicar el numero de columnas y de filas Incluso, podemos generar paneles basados en dos variables categóricas ```r ggplot() + geom_*(aes(...)) + facet_grid(var1 ~ var2) ``` --- <div class="my-header"></div> ## Tu Turno 6: 1. Con la ayuda de la guía rapida intenta reproducir este gráfico que indica con una línea punteada el año del importante terremoto en Haití. ¿Puedes cambiarlo por algún otro evento relevante para este gráfico? 2. Quita la línea y modifícalo para que se vea en paneles ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-43-1.png)<!-- --> --- <div class="my-header"></div> ## Combinando gráficos: `patchwork` El paquete `patchwork` es muy útil para combinar gráficos Al igual que los datos y los vectores, los gráficos también pueden guardarse en una variable ```r g1 <- ggplot(data_4ta_Ronda) + geom_histogram(aes(b10_tamano_hogar),binwidth = 1) ``` ```r g2 <- ggplot(data_4ta_Ronda) + geom_bar(aes(b6_departamento, fill = b6_departamento)) + coord_flip() + theme(legend.position = "none") ``` ```r g3 <- ggplot(data_4ta_Ronda) + geom_point(aes(b10_tamano_hogar, e1_total)) ``` --- <div class="my-header"></div> ## Combinando gráficos: `patchwork` ```r #install.packages("patchwork") library(patchwork) g1 + g2 ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-47-1.png)<!-- --> --- <div class="my-header"></div> ## Combinando gráficos: `patchwork` ```r #install.packages("patchwork") library(patchwork) (g1 | g3) / g2 ``` ![](04-SLD-visualizacionI_files/figure-html/unnamed-chunk-48-1.png)<!-- --> --- <div class="my-header"></div> ## DESAFIO 2 1. Trabajemos un poco más con la encuesta del dataset `data_4taronda` 2. ¿Cuántas personas respondieron la encuesta? 3. Representa un gráfico de barras que represente el nivel educativo de los encuestados 3. Representa un gráfico de la cantidad de personas con trabajo en el hogar en función de la cantidad de personas del hogar 3. Representa un gráfico por paneles de la distribución de la cantidad de personas que viven en un hogar que discrimine según departamento --- <div class="my-header"></div> ## Resumen - elegir un dataset **data** - elegir un gráfico adecuado **geom_** - mapear las variables con las propiedades estéticas **aes()** --- <div class="my-header"></div> ## Para seguir Puedo hacer muuuchas cosas con `ggplot2` - [R para Ciencia de Datos](https://es.r4ds.hadley.nz/) - [ggplot2: elegant graphics for data analysis](https://ggplot2-book.org/) - [Data Visualization - A practical introduction](https://socviz.co/) Un poco más sobre como arreglar gráficos para publicar: - Títulos y otros textos - Etiquetas - Temas - Colores --- <div class="my-header"></div> ## Licencia y material usado Licencia: [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/deed.es_ES). Este material está inspirado y utiliza explicaciones de: - [R para Clima](https://eliocamp.github.io/r-clima/) de Paola Corrales y Elio Campitelli - [Master the Tidyverse](https://github.com/rstudio-education/master-the-tidyverse-instructors) de Garrett Grolemund Las diapositivas fueron creadas con el paquete `xaringan`.