a veces quiero meter varios graficos directamente en un ppt, eso lo hice con ayudade chatGPT y estas referencias I made a tutorial on setting up Powerpoint templates to automate presentations with R and officeR : r/rstats https://www.reddit.com/r/rstats/comments/m5gfo8/i_made_a_tutorial_on_setting_up_powerpoint/
officeverse https://ardata-fr.github.io/officeverse/
En el proyecto “pareados.ra223” hice un loop de plots e hice que cada plot se imprima en una nueva slide, quedo muy bien
How to Append to List in R? | 5 Methods (With Examples) https://favtutor.com/blogs/r-append-to-list
lo estuve explorando en el proyecto de gse46691, estos 2 recursos me gustaron 22 Parallel Computation | R Programming for Data Science https://bookdown.org/rdpeng/rprogdatascience/parallel-computation.html#hidden-parallelism
Parallel Processing in R https://dept.stat.lsa.umich.edu/~jerrick/courses/stat701/notes/parallel.html
esta es otra opcion interesante: Standard regression functions in R enabled for parallel processing over large data-frames https://www.bioconductor.org/packages/release/data/experiment/vignettes/RegParallel/inst/doc/RegParallel.html
kw: rownumber, nro de fila Add an index (numeric ID) column to large data frame - Stack Overflow https://stackoverflow.com/questions/23518605/add-an-index-numeric-id-column-to-large-data-frame
Remove part of string after “.”. El punto es un caso especial por eso hay que “ecapar” https://stackoverflow.com/questions/10617702/remove-part-of-string-after
a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")
gsub("\\..*","",a)
# [1] "NM_020506" "NM_020519" "NM_001030297" "NM_010281" "NM_011419" "NM_053155"
hay muchas formas de hacerlo, descripto acá: Combining gsubs to replace multiple patterns https://www.roelpeters.be/combining-gsubs-to-replace-multiple-patterns-in-r-solved/
acá la mejor solucion, pero hay varias opciones descriptas en la pagina
https://forum.posit.co/t/download-a-gzipped-file-and-decompress-it/15809
ejemplo
link="https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE46691&format=file"
options(timeout=300) # aca configuro el tiempo porque tiene que alcanzar para hacer toda la descarga
# opcion 1
download.file(link, "prueba.tar")
# opcion 2
download.file(link, "prueba.tar", method = "curl") # me da las estadisticas de la descarga, y no me queda claro si corta si se le acaba el tiempo
sacar columna con alguna NA
tabla[ , colSums(is.na(tabla)) == 0]
tabla[ , apply(tabla, 2, function(x) !any(is.na(x)))]
library(dplyr)
tabla %>%
select_if(~ !any(is.na(.)))
# Remove columns where all values are NA
tabla %>%
select(where(~!all(is.na(.))))
# Remove columns with at least one NA
tabla %>%
select(where(~!any(is.na(.))))
Pegar en clipboard :
https://statisticsglobe.com/copy-data-frame-clipboard-r
#esto es para que no corro nninguno de los codigos que están en los chunks
clipr::write_clip(dato.a.pegar)
Que la funcion apply me devuelva un dataframe:
dataframe - R: apply-like function that returns a data frame? - Stack Overflow: https://stackoverflow.com/questions/36982755/r-apply-like-function-that-returns-a-data-frame
apply:
as.data.frame(apply(iris[, 1:4], 2, summary))
sapply:
as.data.frame(sapply(iris[, 1:4], summary))
lapply:
do.call(cbind, lapply(iris[, 1:4], summary))
Cambiar los valores de una columna en base a una tabla de equivalencias:
Recode values based on look up table with dplyr (R) - Stack Overflow: https://stackoverflow.com/questions/66231321/recode-values-based-on-look-up-table-with-dplyr-r
seleccionar.nombres.interes=function(lista.entrada){
require(shiny)
require(clipr)
# Define la UI
ui <- fluidPage(
titlePanel("Selecciona nombres"),
sidebarLayout(
sidebarPanel(
# Crear una lista de checkbox
uiOutput("checkboxes"),
actionButton("copy", "Copiar selección")
),
mainPanel(
textOutput("selected_names")
)
)
)
# Define el servidor
server <- function(input, output, session) {
# Lista de nombres de ejemplo
nombres <- lista.entrada
# Generar dinámicamente los checkboxes
output$checkboxes <- renderUI({
checkboxGroupInput("names", "Nombres", choices = nombres)
})
# Mostrar los nombres seleccionados
observeEvent(input$copy, {
# Formatear los nombres seleccionados como un vector de caracteres
selected_names <- paste0('"', input$names, '"', collapse = ", ")
formatted_names <- paste("c(", selected_names, ")", sep = "")
output$selected_names <- renderText({
formatted_names
})
# Copiar los nombres seleccionados al portapapeles
write_clip(formatted_names)
})
}
# Ejecutar la aplicación
shinyApp(ui = ui, server = server)
}
funcion
# Función para encontrar caracteres especiales en un vector de strings
encontrar_caracteres_especiales <- function(vector_cadenas) {
# Definir caracteres especiales
caracteres_especiales <- c("!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "+", "=",
"{", "}", "[", "]", ":", ";", "'", "\"", ",", "<", ">", "?", "/",
"\\", "|", "~", "`", " ", "°")
# Inicializar un vector para almacenar los caracteres especiales encontrados
encontrados <- c()
# Recorrer cada cadena en el vector
for (cadena in vector_cadenas) {
# Recorrer cada carácter especial
for (caracter in caracteres_especiales) {
# Si el carácter especial está en la cadena, añadirlo al vector de encontrados
if (grepl(caracter, cadena, fixed = TRUE)) {
encontrados <- unique(c(encontrados, caracter))
}
}
}
# Devolver los caracteres especiales encontrados
return(encontrados)
}
# Ejemplo de uso
# vector_cadenas <- c("hola@mundo", "mi variable", "mi-variable", "test#123")
# caracteres_encontrados <- encontrar_caracteres_especiales(vector_cadenas)
# print(caracteres_encontrados)
uzarlo para reemplazar cosas
los hice para el analisis de nirolas de RIRS, tengo el codigo en esa carpeta del proyecto de R y en el github, las referencias: Drawing Nomograms with R: applications to categorical outcome and survival data - PMC https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5451623/
Biostatistics for Biomedical Research – 9 Introduction to the R rms Package: The Linear Model https://hbiostat.org/bbr/rmsintro#nomograms-overall-depiction-of-fitted-models
ESTA FUE LA REFERENCIAS MAS IMPORTANTE: RPubs - Demo of a nomogram https://rpubs.com/clayford/nomogram
nomogram function - RDocumentation https://www.rdocumentation.org/packages/rms/versions/6.8-0/topics/nomogram
crear heatmap con ggplot y geom_tiles: ES MUY IMPORTANTE COMO SE REORDENA LA DATA
r - Create heatmap with values from matrix in ggplot2 - Stack Overflow: https://stackoverflow.com/questions/14290364/create-heatmap-with-values-from-matrix-in-ggplot2
ejemplo
library(survival)
library(survminer)
fit <- survfit(Surv(time, status) ~ sex, data = lung)
p=ggsurvplot(fit,
legend.labs=c("leyenda A","leyenda B"))
p
# cambiar y poner la leyenda que quieras
# la barra "/" gnera problemas, seguro hay soluciones... pero hay que buscar
# queriamos poner una "/", pero genera problemas
p$plot +
scale_color_discrete(labels=c("a",bquote(S[L])))
r_tips/tutorials/dv-volcano_plots_with_ggplot/dv-volcano_plots_with_ggplot.md at master · erikaduan/r_tips https://github.com/erikaduan/r_tips/blob/master/tutorials/dv-volcano_plots_with_ggplot/dv-volcano_plots_with_ggplot.md
Visualization of Volcano Plots in R - Samuel’s Blog https://samdsblog.netlify.app/post/visualizing-volcano-plots-in-r/
Ejemplo basado en la referencia de samdsblog
# data inventada
grafico=structure(list(nombre = c("Angiopoetin.2", "G.CSF", "SCF", "GM.CSF",
"Tenascin.C", "IFN.gamma", "BMP.9", "IL.1.alpha", "Leptin", "IL.1.beta",
"IL.2", "TRAIL", "IL.4", "sIL.6R", "IL.5", "EGF", "IL.6", "Endoglin",
"IL.7", "Endothelin.1", "IL.9", "FGF.2", "Dkk.1", "IL.10", "HGF",
"IL.12.p40", "IL.12.p70", "Periostin", "PIGF.2", "IL.13", "IL.15",
"Galectin.1", "IL.17", "IP.10", "KC", "MCP.1", "MIP.1.alpha",
"SDF.1", "MIP.1.beta", "Osteonectin", "FGF.23", "MIP.2", "Galectin.3",
"RANTES", "VEGF", "TNF.alpha", "HGFR", "Vitronectin", "IGF.1",
"MMP.2", "Osteopontin", "MMP.9", "Axl", "TGFbeta.1", "TGFbeta.3",
"TGFbeta.2"), p.val = c(0.839225653739129, 0.590331216274014,
0.110405888258566, 0.726427295531733, 0.712632870904764, 0.609797293096357,
0.791116679604495, 0.924051281290938, 0.625065524381482, 0.164216632209828,
0.0374188783270202, 0.253926026382899, 0.00502033890552983, 0.0444988131513101,
0.500973981436344, 0.135623397748239, 0.385677256244151, 0.0592602010981502,
0.26372607315013, 0.741082397494451, 0.0473399025871028, 0.0807895503656673,
0.0460078024864051, 0.252268947025709, 0.0189131478245569, 0.108798850299131,
0.0265230280265309, 0.0568692491885416, 0.172952122260311, 0.033878092031299,
0.0636308655535189, 0.647343978309613, 0.24783807917475, 0.00461818386311467,
0.6805106862445, 0.765356450812079, 0.606535475416779, 0.0042714310750879,
0.141301107979996, 0.0678153116263779, 0.00360003777822301, 0.269324261087968,
0.143996669034468, 0.000172278830267783, 0.0526939946746104,
0.213647361245845, 0.958857640884594, 0.91020693922827, 0.647411858024726,
0.218442725468614, 0.187707075647927, 0.162796779100887, 0.27569271077264,
0.767878211810357, 0.565229408870377, 0.933523072679823), fold.change = c(1.14462198648667,
1.63943467769735, 0.672828326984325, 1.54121687929343, 0.927610425019125,
1.28894866621834, 0.901481481481481, 1.02705627705628, 1.12426708672442,
0.412400225751834, 1.31049679487179, 0.64589759407773, 0.434742220157919,
0.503091983477087, 1.39625167336011, 0.523105380321981, 0.81758345086977,
0.427227147661266, 0.413375113383359, 0.969568892645816, 4.68827872634979,
0.475721990010142, 0.27665161539576, 0.585392427720923, 0.337235750602087,
0.579612685113732, 0.378520604802846, 2.32735849056604, 0.569377990430622,
0.598081952920663, 0.173809813709972, 1.07024567788899, 0.625175808720112,
0.346467697579009, 0.855351976856316, 0.892391398220917, 0.882838621630843,
0.527358897027143, 0.541313320825516, 1.80747522889753, 0.560338335989353,
0.547165155160713, 0.755162030398624, 0.336429739414814, 0.0683343502135448,
0.540880503144654, 0.967997236542355, 1.05568057686929, 0.84081690089142,
1.36532656301803, 1.65575498433849, 0.248127204693699, 0.658866602992678,
1.46657726598184, 1.65849949307198, 1.07646565951504), Expression = c("Unchanged",
"Unchanged", "Unchanged", "Unchanged", "Unchanged", "Unchanged",
"Unchanged", "Unchanged", "Unchanged", "Unchanged", "Up-regulated",
"Unchanged", "Down-regulated", "Down-regulated", "Unchanged",
"Unchanged", "Unchanged", "Unchanged", "Unchanged", "Unchanged",
"Up-regulated", "Unchanged", "Down-regulated", "Unchanged", "Down-regulated",
"Unchanged", "Down-regulated", "Unchanged", "Unchanged", "Down-regulated",
"Unchanged", "Unchanged", "Unchanged", "Down-regulated", "Unchanged",
"Unchanged", "Unchanged", "Down-regulated", "Unchanged", "Unchanged",
"Down-regulated", "Unchanged", "Unchanged", "Down-regulated",
"Unchanged", "Unchanged", "Unchanged", "Unchanged", "Unchanged",
"Unchanged", "Unchanged", "Unchanged", "Unchanged", "Unchanged",
"Unchanged", "Unchanged")), class = "data.frame", row.names = c(NA,
-56L))
library(tidyverse)
library(ggrepel)
# para colorear segun el cambio
grafico <- grafico %>%
mutate(
Expression = case_when(fold.change > 1 & p.val <= 0.05 ~ "Up-regulated",
fold.change < 1 & p.val <= 0.05 ~ "Down-regulated",
TRUE ~ "Unchanged")
)
top=10
# paraa agregar labels
top_genes <- bind_rows(
grafico %>%
filter(Expression == 'Up-regulated'),
grafico %>%
filter(Expression == 'Down-regulated'),
grafico %>%
filter(Expression == 'Unchanged') %>%
arrange(desc(abs(log2(fold.change)))) %>%
head(top),
grafico %>%
filter(Expression == 'Unchanged') %>%
arrange(p.val) %>%
head(top)
)
# en caso de tener labels repetidas
top_genes=top_genes[!duplicated(top_genes$nombre),]
# graficar
ggplot(grafico, aes(x=log2(fold.change), y=-log10(p.val)))+
geom_point()+
# geom_vline(xintercept = c(-0.6, 0.6), col = "gray", linetype = 'dashed') +
geom_vline(xintercept = 0, col = "gray", linetype = 'dashed') +
geom_hline(yintercept = -log10(0.05), col = "gray", linetype = 'dashed') +
geom_point(aes(color = Expression)) +
xlab(expression("log"[2]*"FC")) +
ylab(expression("-log"[10]*"p-val"))+
scale_color_manual(values = c("dodgerblue3", "gray50", "firebrick3")) +
guides(colour = guide_legend(override.aes = list(size=1.5))) +
geom_label_repel(data = top_genes,
mapping = aes(x=log2(fold.change), y=-log10(p.val), label=nombre),
size = 3)+
ggtitle("Right: Tratamiento vs Control")
Gatos en ggplot2 con ggcats | R CHARTS https://r-charts.com/es/miscelanea/ggcats/
para evitar cierta aleatoriedad de la hora de agregar colores a factores o caracteres, esta bueno directamente hacer un vetor con nombres que denpues matchee nombre a color
eje x arriba, on top:
r - Putting x-axis at top of ggplot2 chart - Stack Overflow: https://stackoverflow.com/questions/26838005/putting-x-axis-at-top-of-ggplot2-chart
cambiar nombres genes, convertir nombres mapear codigos ID: https://www.gungorbudak.com/blog/2018/08/07/convert-gene-symbols-to-entrez-ids-in-r/
atributos duplicados, el mismo id me da mas de un resultado
genes homologos humano raton: esto lo explico muy bien en un mail que le mande a pablo sanchis, usando biomart
Problemas de conexion de biomart:
BioMart: connection fails: https://www.biostars.org/p/315520/
biomaRt server error, and mirrors do not help: https://support.bioconductor.org/p/9143914/
buenas referencias para biomart:
Accessing Ensembl annotation with biomaRt : https://bioconductor.org/packages/release/bioc/vignettes/biomaRt/inst/doc/accessing_ensembl.html
how to retrieve mouse (mm10) gene information from Ensemble using Biomart in R :https://www.biostars.org/p/147351/
Guia: https://quarto.org/docs/guide/
fechas / date: https://quarto.org/docs/reference/dates.html
# ejemplos en el yaml
---
date: 03/07/2005
date-format: long
---
---
date: today
date-format: long
---
https://quarto.org/docs/authoring/figures.html
** ojo! figura no es lo mismo que imagen. La figura tiene caption y la imagen no veo que esto esta generando muchos problemas y funciona en forma difernte segun la version de quarto (ej: 3.5 vs 5) https://github.com/quarto-dev/quarto-cli/issues/6509 https://github.com/quarto-dev/quarto-cli/issues/4415 https://github.com/quarto-dev/quarto-cli/discussions/3508 https://github.com/quarto-dev/quarto-cli/discussions/5701
las figuras tienen “auto-strech”, asique una opciones es ponerle caption a las imagenes parq que tengan la propiedad de auto strech y center si asi lo quisiera

codigo frecuente presentaciones
:::{.incremental}
- Eat spaghetti
- Drink wine
:::
:::: {.columns}
::: {.column width="40%"}
contents...
:::
::: {.column width="60%"}
contents...
:::
::::
referencias clave
Revealjs https://quarto.org/docs/presentations/revealjs/#slide-backgrounds
codigo fuente de la presentacion https://github.com/quarto-dev/quarto-web/blob/main/docs/presentations/revealjs/demo/index.qmd
Advanced Reveal https://quarto.org/docs/presentations/revealjs/advanced.html
Reveal Themes https://quarto.org/docs/presentations/revealjs/themes.html
Quarto – Quarto Presentations https://quarto.org/docs/presentations/revealjs/demo/#/title-slide
Beautiful Reports and Presentations with Quarto https://thomasmock.quarto.pub/reports-presentations/#/title-slide
Get Started with Quarto – presentations https://rstudio-conf-2022.github.io/get-started-quarto/materials/05-presentations.html#/revealjs-vs-xaringan
Aunque una crea que deberia ser mas facil, no hay una manera de hacer en simultaneo que exporte presentacion y PDF. Por userte alguien hizo una extension gratuita que parece que puede hacer eso: Quarto Templates for Lecturers and Educators https://jmablog.com/post/quarto-templates/
aca tambien hay info al respecto How to convert R reveal.js presentation to pdf? - Stack Overflow https://stackoverflow.com/questions/40778333/how-to-convert-r-reveal-js-presentation-to-pdf
Quarto – Using R https://quarto.org/docs/computations/r.html
Quarto – Execution Options https://quarto.org/docs/computations/execution-options.html
How can I specify global and local chunk options for a quarto pdf book? - Stack Overflow https://stackoverflow.com/questions/73264233/how-can-i-specify-global-and-local-chunk-options-for-a-quarto-pdf-book
Make Text Smaller in a Section / List · quarto-dev/quarto-cli · Discussion #3696 https://github.com/quarto-dev/quarto-cli/discussions/3696
Si al tengo en el enviroment, y quiero que me la renderice, las opciones son las que estan acá
r - Convert dataframe to markdown table in Quarto - Stack Overflow https://stackoverflow.com/questions/76135432/convert-dataframe-to-markdown-table-in-quarto
r - Using Markdown formatting in table using kable in quarto - Stack Overflow https://stackoverflow.com/questions/72516135/using-markdown-formatting-in-table-using-kable-in-quarto
Quarto – Tables https://quarto.org/docs/authoring/tables.html
lo de simplemardown no lo pude intalar, asique no lo prome el metodo de knit parece andar bien, pero despues la tabla me queda demasiado grande para la slida. La colución rapida que aplica fue achicar la letra
Aca hay libro de referencia: R Markdown: The Definitive Guide https://bookdown.org/yihui/rmarkdown/html-document.html#code-folding
de donde saque algunas cosas del theme o formato, especialmente el capitulo 3 tiene buenas cosas del YAML para HTML https://bookdown.org/yihui/rmarkdown/html-document.html
en particular, para la parte de los themes, aca hay 2 referencias:
https://bootswatch.com/3/ (esto se usa por default en la parte de theme)
aca hay otra referencia interesante para themes https://rpubs.com/ranydc/rmarkdown_themes
r - Is there a global command line knit option as eval=FALSE for all chunks? - Stack Overflow https://stackoverflow.com/questions/68031768/is-there-a-global-command-line-knit-option-as-eval-false-for-all-chunks
agregar la fecha, date, r - YAML current date in rmarkdown - Stack Overflow https://stackoverflow.com/questions/23449319/yaml-current-date-in-rmarkdown
4.8 Update the date automatically | R Markdown Cookbook https://bookdown.org/yihui/rmarkdown-cookbook/update-date.html
ejemplos
usualmente es medio problematico guardar los datos que escupe ggsurvplot
Metodo 1: consiste en crear una funcion que o hace compatible con GGsave. Simpleente se ejecuta esta funcion una vez, y despues cuando hacemos el ggsave, funciona fuente: https://stackoverflow.com/questions/75071135/kaplan-meier-curve-with-ggsurvplot-with-transparent-background
grid.draw.ggsurvplot <- function(x) survminer:::print.ggsurvplot(x, newpage = FALSE) # esto se corre solo una vez para que la funcion este en el enviroment
ggsave("test_survplot.png", surv_plot_out)
metodo 2: imprimir el plot
fuente: https://stackoverflow.com/questions/48631144/ggsurvplot-save-output-with-correct-dimensions
arme 2 shiny apps muy basicas para el proyecto de nicolas de RIRS, estan los srcrips en las carpetas “analisis.nicolas.app” y ” analisis.nicolas.app.eco”
Las referencias para hacer esto fueron + Shiny - Hosting and deployment: https://shiny.posit.co/r/deploy.html
shinyapps.io: https://www.shinyapps.io/admin/#/dashboard
Shiny - Getting started with shinyapps.io : https://shiny.posit.co/r/articles/share/shinyapps/?_gl=1*1o7utq1*_ga*MTcyNjE4NTg2MS4xNzEyMzQ4MTQw*_ga_HXP006LBGY*MTcxMjM0ODE0MC4xLjEuMTcxMjM0ODE2NS4wLjAuMA..
las que están funcionando las puedo ver aca; https://www.shinyapps.io/admin/#/applications/running
graficar 2 o mas curvas ROC juntas siempre es medio un dolor de cabeza y no encuentro un metodo ideal.
La mejor aproximación que estoy usando es esta de aca, que es un paquete con muchas opciones:
Generate ROC Curve Charts for Print and Interactive Use: https://cran.r-project.org/web/packages/plotROC/vignettes/examples.html un buen uso de ese paquete es en el trabajo de nicolas RIRS.
un recursos para graficar muy rapidamente: Graphs in R using ggplot2: Receiver Operating Characteristic Curves: https://rowannicholls.github.io/R/graphs/ggplot2/receiver_operating_characteristic.html
para generar data sintetica o simulaciones de datos que respondan a un AUC r - Generate synthetic data given AUC - Cross Validated https://stats.stackexchange.com/questions/422926/generate-synthetic-data-given-auc
otros recursos que paren interesantes, per no los exploré: Some R Packages for ROC Curves · R Views https://rviews.rstudio.com/2019/03/01/some-r-packages-for-roc-curves/
How to pool ROC curves in R to better understand a model’s performance (CC135) https://riffomonas.org/code_club/2021-08-09-roc-curves
esto lo hice en muchos lugares, incluido tesis, pero la version mas prolija CREO que es la que dejé en proyectos r>ADT_santi y el archivo es analisis_general_pre_y_post_ADT
How to use GSVA for the RNA-seq RPKM file https://www.biostars.org/p/291284/
DESeq2 and edgeR should no longer be the default choices for large-sample differential gene expression analysis | by Jingyi Jessica Li | Towards Data Science https://towardsdatascience.com/deseq2-and-edger-should-no-longer-be-the-default-choice-for-large-sample-differential-gene-8fdf008deae9
estos recursos me resultaron interesantes, todo lo que hice lo aprendi con el proyecto del garrahan Shiny UI Editor Project Walkthrough || Nick Strayer || RStudio - YouTube https://www.youtube.com/watch?v=gYPnLiudtGU&ab_channel=PositPBC
Nick Strayer | A new way to build your Shiny app’s UI | RStudio (2022) - YouTube https://www.youtube.com/watch?v=UIaigpCAIqE&ab_channel=PositPBC
multiple univariate regressions https://stackoverflow.com/questions/71637805/tidy-multiple-univariate-regressions
Estos 3 recursos me gustaron mucho y me parecieron bien descriptos
Performing univariate and multivariate logistic regression in gene expression data https://www.biostars.org/p/373752/
Building a predictive model by a list of genes https://www.biostars.org/p/357735/#357739
Resources for gene signature creation https://www.biostars.org/p/273798/#273805
el PCA me suele ser mas complicado de lo que espero, parece bastante straight foward, pero siempre algo me hace lio, especialmente la parte de graficarlo es mas engorrosa de lo que yo considero deberia ser.
El principal metodo para graficarlo es factoextra https://rpkgs.datanovia.com/factoextra/reference/fviz_pca.html
que permite graficar los siguietntes parametros - fviz_pca_ind(): Graph of individuals, es decir, grafica los puntos - fviz_pca_var(): Graph of variables, es decir, grafic las linesas - fviz_pca_biplot(): Biplot of individuals and variables
uno de los problemas frecuentes con esto es ajustar los colores y las formas de los puntos, nunca me sale bien de una. Aca lo discuten y dan una posible solucion https://stackoverflow.com/questions/46934303/pca-change-colours-of-clusters
library(factoextra)
res.pca <- prcomp(iris[, -5], scale = TRUE)
# problema
fviz_pca_ind(res.pca, geom="point", pointsize = 1, habillage=iris$Species, addEllipses=TRUE, ellipse.level=0.95)
# solucion
fviz_pca_ind(res.pca, geom="point",
pointsize = 1,
habillage=iris$Species,
addEllipses=TRUE,
ellipse.level=0.95,
palette = c("green", "orange", "grey") #change colors
) +
scale_shape_manual(values=c(2, 2, 2)) #change shapes, aca pongo 3 veces lo mismo para que de 3 veves el mismo forma