library(tidyr) library(dplyr) library(ggplot2) library(reshape2) #Please modify the path to match the directory on your own computer before running the script. setwd("/Users/Kimashi/Documents/ws/tunome/BlastHomolog") #All CSV files should be placed inside the DName folder directly under the specified path above. DName="BER" ## Extract gene names from filenames files=list.files(DName) files2=files[grepl("^BlastCompTable_",files)] files3=gsub("BlastCompTable_","",files2) genes=gsub(".csv","",files3) # Test loading one table df <- read.table(paste0(DName,"/BlastCompTable_",genes[1],".csv"), header = TRUE, stringsAsFactors = FALSE, sep=",") # Get species list splist=unique(df$SPECIES[df$SPECIES!=""]) # Create result table result <- setNames(data.frame(matrix(ncol = length(splist)+1, nrow = length(genes))), c("GeneName",splist)) result$GeneName=genes for(i in seq_along(genes)){ df <- read.table(paste0(DName,"/BlastCompTable_",genes[i],".csv"), header = TRUE, stringsAsFactors = FALSE, sep=",") # Fill empty species names with previous value df_filled <- df %>%mutate(SPECIES = ifelse(SPECIES == "", NA, SPECIES)) %>%fill(SPECIES) # Extract LOCUS (remove variant suffix) df_filled$LOCUS <- sub("\\.[^.]+$", "", df_filled$SSEQID) # Remove duplicated variants df_unique <- df_filled[!duplicated(df_filled[,c("SPECIES","LOCUS")]), ] # Remove NA rows df_omit<-na.omit(df_unique) for(j in seq_along(splist)){ result[i,splist[j]]=sum(df_omit$SPECIES==splist[j]) } } # Convert to matrix mat <- as.matrix(result[, -1]) rownames(mat) <- result$GeneName # Format species names colnames(mat) <- sub("^(.)(.)", "\\1. \\2", colnames(mat)) colnames(mat)[colnames(mat) == "P. egea"] <- "Pegea sp." # Normalize each row by the maximum value row_max <- apply(mat, 1, max) row_max[row_max == 0] <- 1 mat_scaled <- mat / row_max ########################## ###########GGplot2####### ########################## mat=mat_scaled # Convert matrix to long format mat_long <- melt(mat) colnames(mat_long) <- c("Gene", "Species", "Value") # Flag zero values mat_long$is_zero <- mat_long$Value == 0 # Draw heatmap g<-ggplot(mat_long, aes(x = Species, y = Gene, fill = Value)) + geom_tile(color = "grey50", size = 0.3) + geom_tile(data = mat_long[mat_long$is_zero, ], aes(x = Species, y = Gene), color = "black", size = 0.4, fill = NA) + # 0 のセルに太枠だけ描く scale_fill_gradient(low = "white", high = "red") + theme_minimal(base_size = 10) + theme(axis.text.x = element_text(angle = 90, hjust = 1, face="italic")) # Save figure g ggsave(paste0(DName,"/",DName,".png"), plot = g)