En este documento mostraré algunos gráficos que suelo usar en mis anánilisis, o que me parecen útiles y quiero guardar el código para cuando necesite usarlo.
En cada sección del documento hare una clase de gráfico con un cógido general para luego poder adaptarlo a la data con la que este (o ustedes esten) trabajando. Espero que este documento les sea tan útil a ustedes como a mi, y con el tiempo iré agregando más gráficos.
Aquí se muestran graficos de regresión lineal mostrando la interacción de varios factores y en cada uno la ecuación de la línea. Utilizaremos los paquetes “ggplot2” (1) y “ggpmisc” (2).
F1 <- c(rep("F1_1",15),rep("F1_2",15),rep("F1_3",15))
F2 <- rep(c(rep("F2_1",5),rep("F2_2",5),rep("F2_3",5)),3)
var1 <- rnorm(45)
var2 <- rnorm(45)
data <- data.frame(F1,F2,var1,var2)
rm(F1,F2,var1,var2)
str(data)
## 'data.frame': 45 obs. of 4 variables:
## $ F1 : Factor w/ 3 levels "F1_1","F1_2",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ F2 : Factor w/ 3 levels "F2_1","F2_2",..: 1 1 1 1 1 2 2 2 2 2 ...
## $ var1: num -0.558 0.371 1.148 0.976 -0.553 ...
## $ var2: num 0.41221 2.4752 0.00302 -1.68079 0.21381 ...
# instalar librerias y cargarlas
#install.packages("ggplot2")
#install.packages("ggpmisc")
library(ggplot2)
library(ggpmisc)
ggplot(data,aes(x=var1,y=var2)) +
geom_point(size=2.5) +
geom_smooth(fill=NA,method = "lm",size=0.3) +
facet_grid(F1~F2, scales="free") +
ggpmisc::stat_poly_eq(formula = y ~ x,aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse=TRUE, size= 3, label.x.npc = "center",label.y.npc = 1)
Para construir el heatmap interactivo usaremos el paquete “iheatmapr” (3). Instalar este paquete requiere de una dependencia que no se encuentra en el repositorio del CRAN, sino en Bioconductor. Para instalar “iheatmapr” basta con ejecutar las siguientes tres líneas:
source("https://bioconductor.org/biocLite.R")
biocLite("S4Vectors")
install.packages("iheatmapr")
En la página de iheatmapr hay disponibles varios ejemplos de como usar el paquete.
Data modelo para el heatmap:
data <- matrix(c(-1.20407223, -1.3448128, 0.74281705, 0.8023334, 1.06975148, 1.1162123, 1.46995500, 0.5705723, 0.93625766, -0.2201465, 0.02411537, 1.1267230, 0.62169057, -0.4648535, -0.57408033, 0.7151795, 2.41264147, 1.2718797, -0.86460122, -0.1059739, 0.01108491, -0.1185602, 1.21015886, 0.4689901), nrow = 6, dimnames = list(c("F1","F2","F3","F4","F5","F6"),c("C1","C2","C3","C4")),byrow = T)
head(data)
## C1 C2 C3 C4
## F1 -1.20407223 -1.3448128 0.74281705 0.8023334
## F2 1.06975148 1.1162123 1.46995500 0.5705723
## F3 0.93625766 -0.2201465 0.02411537 1.1267230
## F4 0.62169057 -0.4648535 -0.57408033 0.7151795
## F5 2.41264147 1.2718797 -0.86460122 -0.1059739
## F6 0.01108491 -0.1185602 1.21015886 0.4689901
Heatmap simple:
# Librería
library(iheatmapr)
# Heatmap interactivo
main_heatmap(data, colors = "Blues", name = "Variable", colorbar_position = 1) %>%
add_row_labels() %>%
add_col_labels(side="top", textangle = 0) %>%
add_row_title("Filas") %>%
add_col_title("Columnas", side="top")
Además el paquete incluye la función save_iheatmap()
, que permite guardar el heatmap ya sea como un gráfico interactivo (html) o estático (png).
Añadiendo dendogramas.
main_heatmap(data, colors = "Blues", name = "Variable", colorbar_position = 1) %>%
add_row_labels() %>%
add_col_labels(side="top", textangle = 0) %>%
add_row_clustering() %>%
add_col_clustering() %>%
add_row_title("Filas") %>%
add_col_title("Columnas", side="top")
main_heatmap(data, colors = "Blues", name = "Variable", colorbar_position = 1) %>%
add_row_labels() %>%
add_col_labels(side="top", textangle = 0) %>%
add_row_clustering(k = 3) %>%
add_col_clustering() %>%
add_row_title("Filas") %>%
add_col_title("Columnas", side="top") %>%
add_col_summary(groups = TRUE, side = "bottom")
main_heatmap(data, colors = "Blues", name = "Variable", colorbar_position = 1) %>%
add_row_labels() %>%
add_col_labels(side="top", textangle = 0) %>%
add_row_clustering(k = 3, method = "kmeans") %>%
add_col_clustering() %>%
add_row_title("Filas") %>%
add_col_title("Columnas", side="top")
Añadiendo cluster arbitrarios.
main_heatmap(data, colors = "Blues", name = "Variable", colorbar_position = 1) %>%
add_row_labels() %>%
add_col_labels(side="top", textangle = 0) %>%
add_row_clustering(method = "groups", groups = c("A","A","B","B","A","A")) %>%
add_col_clustering() %>%
add_row_title("Filas") %>%
add_col_title("Columnas", side="top")
Añadiendo grupos.
main_heatmap(data, colors = "Blues", name = "Variable", colorbar_position = 1) %>%
add_row_labels() %>%
add_col_labels(side="top", textangle = 0) %>%
add_row_clustering() %>%
add_col_clustering() %>%
add_row_title("Filas") %>%
add_col_title("Columnas", side="top") %>%
add_row_annotation(data.frame("Grupo" = c("B","B","A","A","C","B")),colors = list("Grupo" = c("red","blue","green"))) %>%
add_col_summary(groups = TRUE, side = "bottom")
En ciertas ocaciones necesitamos prsentar dos gráficos juntos para poder explicar nuestros resultados, por ejemplo necesitamos juntar un gráfico de barras junto a uno de dispersión. Las librerías “gridExtra”(4) y “cowplot”(5) pueden usarse para juntar gráficos. Recientemente ha salido un nuevo paquete, “patchwork”(6), que resulta más fácil de usar, por el momento no se encuentra en el CRAN pero se puede instalar fácilmente con los siguente comandos:
# install.packages("devtools")
devtools::install_github("thomasp85/patchwork")
En el artículo de r-exercises muestran ejemplos de como usar esta librería, algunos de los cuales he replicado aqui.
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p1 + p2
p1 + p2 + patchwork::plot_layout(ncol = 1, heights = c(3, 1))
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
p1 + p2 - p3 + plot_layout(ncol = 1)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
p4 <- ggplot(mtcars) + geom_bar(aes(carb))
p5 <- ggplot(mtcars) + geom_violin(aes(cyl, mpg, group = cyl))
p1 +
p2 +
(p3 +
p4 +
plot_layout(ncol = 1)
) +
p5 +
plot_layout(widths = c(2, 1))
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
(p1 | p2 | p3) / p4
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
## Session info -------------------------------------------------------------
## setting value
## version R version 3.4.3 (2017-11-30)
## system x86_64, darwin15.6.0
## ui X11
## language (EN)
## collate en_US.UTF-8
## tz America/Lima
## date 2018-05-28
## Packages -----------------------------------------------------------------
## package * version date source
## assertthat 0.2.0 2017-04-11 CRAN (R 3.4.0)
## backports 1.1.2 2017-12-13 CRAN (R 3.4.3)
## base * 3.4.3 2017-12-07 local
## bindr 0.1.1 2018-03-13 CRAN (R 3.4.4)
## bindrcpp 0.2.2 2018-03-29 CRAN (R 3.4.4)
## BiocGenerics 0.22.1 2017-10-07 Bioconductor
## colorspace 1.3-2 2016-12-14 CRAN (R 3.4.0)
## compiler 3.4.3 2017-12-07 local
## datasets * 3.4.3 2017-12-07 local
## devtools 1.13.5 2018-02-18 CRAN (R 3.4.3)
## digest 0.6.15 2018-01-28 CRAN (R 3.4.3)
## dplyr 0.7.5 2018-05-19 CRAN (R 3.4.3)
## evaluate 0.10.1 2017-06-24 CRAN (R 3.4.1)
## fastcluster 1.1.24 2017-08-21 CRAN (R 3.4.1)
## ggdendro 0.1-20 2016-04-27 CRAN (R 3.4.0)
## ggplot2 * 2.2.1.9000 2018-05-28 Github (tidyverse/ggplot2@4299917)
## ggpmisc * 0.2.17 2018-05-04 CRAN (R 3.4.3)
## glue 1.2.0 2017-10-29 CRAN (R 3.4.2)
## graphics * 3.4.3 2017-12-07 local
## grDevices * 3.4.3 2017-12-07 local
## grid 3.4.3 2017-12-07 local
## gtable 0.2.0 2016-02-26 CRAN (R 3.4.0)
## htmltools 0.3.6 2017-04-28 CRAN (R 3.4.0)
## htmlwidgets 1.2 2018-04-19 CRAN (R 3.4.4)
## iheatmapr * 0.4.3 2017-12-08 CRAN (R 3.4.3)
## jsonlite 1.5 2017-06-01 CRAN (R 3.4.0)
## knitr 1.20 2018-02-20 CRAN (R 3.4.3)
## labeling 0.3 2014-08-23 CRAN (R 3.4.0)
## lazyeval 0.2.1 2017-10-29 CRAN (R 3.4.2)
## magrittr 1.5 2014-11-22 CRAN (R 3.4.0)
## MASS 7.3-50 2018-04-30 CRAN (R 3.4.3)
## memoise 1.1.0 2017-04-21 CRAN (R 3.4.0)
## methods * 3.4.3 2017-12-07 local
## munsell 0.4.3 2016-02-13 CRAN (R 3.4.0)
## parallel 3.4.3 2017-12-07 local
## patchwork * 0.0.1 2018-05-28 Github (thomasp85/patchwork@6979eb1)
## pillar 1.2.2 2018-04-26 CRAN (R 3.4.3)
## pkgconfig 2.0.1 2017-03-21 CRAN (R 3.4.0)
## plyr 1.8.4 2016-06-08 CRAN (R 3.4.0)
## polynom 1.3-9 2016-12-08 CRAN (R 3.4.0)
## purrr 0.2.4 2017-10-18 CRAN (R 3.4.2)
## R6 2.2.2 2017-06-17 CRAN (R 3.4.0)
## RColorBrewer 1.1-2 2014-12-07 CRAN (R 3.4.0)
## Rcpp 0.12.17 2018-05-18 CRAN (R 3.4.3)
## reshape2 1.4.3 2017-12-11 CRAN (R 3.4.3)
## rlang 0.2.0 2018-02-20 CRAN (R 3.4.3)
## rmarkdown 1.9 2018-03-01 CRAN (R 3.4.3)
## rprojroot 1.3-2 2018-01-03 CRAN (R 3.4.3)
## S4Vectors 0.14.7 2017-10-08 Bioconductor
## scales 0.5.0 2017-08-24 CRAN (R 3.4.1)
## stats * 3.4.3 2017-12-07 local
## stats4 3.4.3 2017-12-07 local
## stringi 1.2.2 2018-05-02 CRAN (R 3.4.3)
## stringr 1.3.1 2018-05-10 CRAN (R 3.4.3)
## tibble 1.4.2 2018-01-22 CRAN (R 3.4.3)
## tidyselect 0.2.4 2018-02-26 CRAN (R 3.4.3)
## tools 3.4.3 2017-12-07 local
## utils * 3.4.3 2017-12-07 local
## withr 2.1.2 2018-03-15 CRAN (R 3.4.4)
## yaml 2.1.19 2018-05-01 CRAN (R 3.4.3)
1. Wickham H. Ggplot2: Elegant graphics for data analysis [Internet]. Springer-Verlag New York; 2009. Available from: http://ggplot2.org
2. Aphalo PJ. Learn r ...as you learnt your mother tongue [Internet]. Leanpub; 2016. Available from: https://leanpub.com/learnr
3. Schep AN, Kummerfeld SK. Iheatmapr: Interactive complex heatmaps in r. Journal of Open Source Software [Internet]. 2017; Available from: http://dx.doi.org/10.21105/joss.00359
4. Auguie B. GridExtra: Miscellaneous functions for “grid” graphics [Internet]. 2017. Available from: https://CRAN.R-project.org/package=gridExtra
5. Wilke CO. Cowplot: Streamlined plot theme and plot annotations for ’ggplot2’ [Internet]. 2017. Available from: https://CRAN.R-project.org/package=cowplot
6. Pedersen TL. Patchwork: The composer of ggplots [Internet]. 2017. Available from: https://github.com/thomasp85/patchwork