Skip to content
Snippets Groups Projects
Commit 31c9c4ec authored by Anta Diop's avatar Anta Diop
Browse files

Upload New File

parent 300774bf
No related branches found
No related tags found
No related merge requests found
---
title: '"Module d''analyse des corrélations des annotations des échantillons"'
output: html_document
---
```{r load_packages, include=FALSE}
# Installer et charger les packages nécessaires (à exécuter une seule fois)
if(!require(GGally)) install.packages("GGally")
if(!require(readr)) install.packages("readr")
if(!require(dplyr)) install.packages("dplyr")
if(!require(ggplot2)) install.packages("ggplot2")
if(!require(corrplot)) install.packages("corrplot")
if(!require(ComplexHeatmap)) {
if(!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("ComplexHeatmap")
}
if(!require(RColorBrewer)) install.packages("RColorBrewer")
if(!require(reshape2)) install.packages("reshape2")
library(GGally)
library(readr)
library(dplyr)
library(ggplot2)
library(corrplot)
library(ComplexHeatmap)
library(RColorBrewer)
library(reshape2)
```
```{r}
# Importer le fichier d'annotations (ex: CSV)
setwd("C:/Users/User/Desktop/projet_visualisation")
annotations <- read.csv("design_test.csv", sep=",", stringsAsFactors = FALSE)
# Aperçu de la structure et résumé des données
glimpse(annotations)
summary(annotations)
# Vérification des valeurs manquantes par colonne
missing_values <- colSums(is.na(annotations))
print(missing_values)
```
2. Séparation et Conversion des Variables
```{r}
# Variables numériques d'origine (pour certaines analyses)
num_data <- annotations %>% select(where(is.numeric))
# Variables catégorielles d'origine (caractère ou facteur)
cat_data <- annotations %>% select(where(~ is.character(.) | is.factor(.)))
cat("Variables numériques détectées : ", paste(colnames(num_data), collapse = ", "), "\n")
cat("Variables catégorielles détectées : ", paste(colnames(cat_data), collapse = ", "), "\n")
```
2.1 Conversion Automatisée pour le Calcul de Corrélation
```{r}
convert_to_numeric <- function(df, date_cols = NULL, drop_cols = NULL, date_format = "%d.%m.%Y") {
# Supprime les colonnes non désirées
if (!is.null(drop_cols)) {
df <- df %>% select(-all_of(drop_cols))
}
df_numeric <- df %>% mutate(across(everything(), ~ {
if (is.numeric(.)) {
return(.)
} else if (is.character(.)) {
# Si la colonne est spécifiée comme date ou peut être parsée en date
if (!is.null(date_cols) && cur_column() %in% date_cols) {
return(as.numeric(as.Date(., format = date_format)))
} else {
parsed_date <- suppressWarnings(as.Date(., format = date_format))
if (all(!is.na(parsed_date))) {
return(as.numeric(parsed_date))
} else {
return(as.numeric(factor(.)))
}
}
} else if (is.factor(.)) {
return(as.numeric(.))
} else {
return(as.numeric(.))
}
}))
return(df_numeric)
}
# Exemple : traiter "experiment" et "extraction" comme dates, et supprimer "sample"
data_numeric <- convert_to_numeric(annotations,
date_cols = c("experiment", "extraction"),
drop_cols = c("sample"))
str(data_numeric)
```
3. Visualisations de Corrélation et Distributions
3.1 Matrice de Corrélation avec corrplot
```{r}
if(ncol(data_numeric) > 1){
cor_matrix <- cor(data_numeric, use = "complete.obs", method = "pearson")
corrplot(cor_matrix, method = "circle", type = "lower",
tl.col = "black", tl.cex = 0.8,
col = colorRampPalette(c("blue", "white", "red"))(200))
} else {
cat("Pas assez de colonnes numériques pour calculer une matrice de corrélation.\n")
}
```
3.2 Heatmap avec ComplexHeatmap
```{r}
if(ncol(data_numeric) > 1){
Heatmap(cor_matrix, name = "Corrélation",
col = colorRampPalette(brewer.pal(8, "RdYlBu"))(50),
column_title = "Heatmap de la matrice de corrélation")
} else {
cat("Pas assez de variables numériques pour générer une heatmap.\n")
}
```
3.3 Pairs Plot des Variables Numériques
```{r}
if(ncol(num_data) > 1){
ggpairs(num_data, title = "Pairs Plot des variables numériques", progress = FALSE)
} else {
cat("Pas assez de variables numériques pour générer un pairs plot.\n")
}
```
3.4 Distribution des Variables Numériques
Pour chaque variable numérique, un histogramme et une courbe de densité sont affichés.
```{r}
numeric_vars <- names(data_numeric)
for (var in numeric_vars) {
p <- ggplot(data_numeric, aes_string(x = var)) +
geom_histogram(aes(y = ..density..), bins = 30, fill = "blue", alpha = 0.5) +
geom_density(color = "red", size = 1) +
labs(title = paste("Distribution de", var),
x = var, y = "Densité") +
theme_minimal()
print(p)
}
```
3.5 Scatter Plots pour Paires de Variables Fortement Corrélées
On identifie les paires de variables dont la corrélation absolue dépasse un seuil (ici 0.7) et on affiche un scatter plot avec une droite de régression.
```{r}
cor_threshold <- 0.7
if(ncol(data_numeric) > 1){
high_cor_pairs <- which(abs(cor_matrix) > cor_threshold & abs(cor_matrix) < 1, arr.ind = TRUE)
high_cor_pairs <- high_cor_pairs[high_cor_pairs[,1] < high_cor_pairs[,2], ]
if(nrow(high_cor_pairs) > 0){
for (i in 1:nrow(high_cor_pairs)) {
var1 <- colnames(cor_matrix)[high_cor_pairs[i, 1]]
var2 <- colnames(cor_matrix)[high_cor_pairs[i, 2]]
p <- ggplot(data_numeric, aes_string(x = var1, y = var2)) +
geom_point(alpha = 0.6) +
geom_smooth(method = "lm", se = FALSE, color = "red") +
labs(title = paste("Scatter Plot de", var1, "vs", var2),
subtitle = paste("Corrélation =", round(cor_matrix[high_cor_pairs[i,1], high_cor_pairs[i,2]], 2))) +
theme_minimal()
print(p)
}
} else {
cat("Aucune paire de variables avec une corrélation absolue supérieure à", cor_threshold, "\n")
}
} else {
cat("Pas assez de variables numériques pour générer des scatter plots.\n")
}
```
3.6 Distribution des Variables Catégorielles
```{r}
cat_vars <- names(cat_data)
for (var in cat_vars) {
p <- ggplot(annotations, aes_string(x = var)) +
geom_bar(fill = "blue", alpha = 0.7) +
labs(title = paste("Distribution de la variable catégorielle :", var),
x = var, y = "Fréquence") +
theme_minimal()
print(p)
}
```
3.7 Visualisation de la Variable sample
```{r}
if("sample" %in% names(annotations)){
p <- ggplot(annotations, aes(x = factor(sample))) +
geom_bar(fill = "steelblue", alpha = 0.7) +
labs(title = "Distribution de la variable 'sample'",
x = "Sample", y = "Fréquence") +
theme_minimal()
print(p)
} else {
cat("La variable 'sample' n'existe pas dans les données.\n")
}
```
3.8 Visualisation Avancée (Matrice Améliorée)
```{r}
# Créer une copie des données pour conversion en facteurs
data_factors <- annotations
# Conversion des colonnes spécifiques en facteurs si elles existent
cols_to_factor <- c("condition", "animal", "experiment", "extraction")
for (col in cols_to_factor) {
if (col %in% names(data_factors)) {
data_factors[[col]] <- as.factor(data_factors[[col]])
}
}
# Supprimer la colonne "sample" pour cette visualisation
if("sample" %in% names(data_factors)) {
data_factors <- data_factors %>% select(-sample)
}
# Définition des couleurs personnalisées
custom_colors <- c("#1B9E77", "#D95F02", "#7570B3") # Vert, Orange, Bleu
# Génération de la matrice de plots avec ggpairs
ggpairs(data_factors,
mapping = aes(color = condition),
lower = list(
continuous = wrap("points", alpha = 0.7, color = custom_colors[1]),
combo = wrap("box_no_facet", outlier.colour = "red")
),
diag = list(
continuous = wrap("densityDiag", alpha = 0.5, fill = custom_colors[2])
),
upper = list(
continuous = wrap("cor", size = 5, color = "black")
)
) +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 10),
axis.text.y = element_text(size = 10),
legend.position = "bottom")
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment