rm(list = ls())
library(openxlsx)
library(dplyr)
## 
## 载入程辑包:'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyr)
library(ggdendro)
library(ggplot2)
dir_path <- "C:\\Users\\liyix\\OneDrive\\Desktop\\"
dir_path_name <- list.files(pattern = ".*xlsx",dir_path,full.names = T, recursive = F)
#dir_path_name
#getSheetNames(grep("data.xlsx",dir_path_name,value = T))
data_1 <- read.xlsx(grep("data.xlsx",dir_path_name,value = T),sheet = 1)
##View(Guide)
#dim(data_1) #[1] 139   9
#head(data_1)
data_1 <- data_1[1:26,]
data_1$Feature <- NULL
colnames(data_1) <- LETTERS[1:ncol(data_1)]
row.names(data_1) <- letters
#View(data_1)
###########################################################dendro_1_LEFT
data_2 <- data_1
##########################
#str(data_2)
#View(data_2)
head(data_2)
##       A     B     C    D E F G H
## a -9.00 -7.00 -5.00 7.33 0 0 1 1
## b  0.00  8.33 -3.00 1.33 0 0 0 1
## c -2.67  0.00 -2.08 4.67 1 2 2 1
## d -9.00  2.00 -1.33 0.00 0 1 1 1
## e    NA    NA -1.33 2.00 0 0 0 0
## f -9.00  0.00 -1.17 4.17 1 1 1 2
##########################
#data_2[is.na(data_2)] <- 0
dd <- dist(scale(data_2), method = "euclidean")
hc <- hclust(dd, method = "complete")
ggdendrogram(hc, rotate = T)

##############################
dend <- as.dendrogram(hc)
dendata <- dendro_data(dend,type = "rectangle")
#add column family to labs dataframe (look like VLOOKUP in excel)
labs <- label(dendata)
###########################################plot
data_plot <- segment(dendata)
labs$y <- -0.1
#head(labs)
#head(data_plot)
#dim(data_2)
p <- ggplot(data_plot) +
  geom_segment(aes(x=x, y=y, xend=xend, yend=yend, color=""),size = .1) + 
  coord_flip() + 
  #geom_text(data=labs,size= 1,
  #          aes(label=label, x=x, y= y),vjust = 0.5,hjust = 0, color = "white")+
  geom_segment(data=labs,aes(x=x, y=y, xend=x, yend=0, color=""),size = .1) +
  scale_colour_manual(values = c("black")) +
  scale_x_continuous(expand = c(0,0),limits = c(0.5,nrow(data_2)+0.5)) +
  scale_y_reverse(expand = c(0.01, 0.01))

p_dendro <- p + theme(legend.position = "none")+ 
  theme(axis.line = element_blank())
p_dendro

#####################################################################denfdro_2_TOP
#data_2[is.na(data_2)] <- 0
data_4 <- data.frame(t(data_2))
#View(data_4)
dd1 <- dist(scale(data_4), method = "euclidean")
hc1 <- hclust(dd1, method = "complete")
ggdendrogram(hc1, rotate = T)

##############################
dend1 <- as.dendrogram(hc1)
dendata1 <- dendro_data(dend1,type = "rectangle")
#add column family to labs dataframe (look like VLOOKUP in excel)
labs1 <- label(dendata1)
data_plot1 <- segment(dendata1)
#labs1$y <- -0.2
head(labs1)
##   x y label
## 1 1 0     A
## 2 2 0     B
## 3 3 0     D
## 4 4 0     C
## 5 5 0     E
## 6 6 0     F
head(data_plot1)
##         x         y   xend      yend
## 1 2.53125 10.995791 1.0000 10.995791
## 2 1.00000 10.995791 1.0000  0.000000
## 3 2.53125 10.995791 4.0625 10.995791
## 4 4.06250 10.995791 4.0625  7.784358
## 5 4.06250  7.784358 2.5000  7.784358
## 6 2.50000  7.784358 2.5000  5.979765
p1 <- ggplot(data_plot1) +
  geom_segment(aes(x=x, y=y, xend=xend, yend=yend, color=""),size = 0.1) + 
  # geom_segment(data=labs1,size= 3,
  #          aes(x=x, y= y, xend = x, yend = 0), color = "green") +
  scale_colour_manual(values = c("black")) +
  scale_x_continuous(expand = c(0, 0), limits = c(0.5,ncol(data_2) + 0.5)) +
  scale_y_continuous(expand = c(0, 0))

p_dendro1 <- p1 + theme(legend.position = "none")+ 
  theme(axis.line = element_blank()) #+
#  labs(x = "", y = "", title = "")  
#theme(panel.background = element_rect(fill = NA, colour = NA),
#      plot.background = element_rect(fill = NA,colour = NA))

p_dendro1

##################################################2___HM-P-VALUE
#colnames(data_1)
data_21 <- data_1
#View(data_21)
data_21$num <- row.names(data_21)
data_3 <- gather(data_21, key = key, value = value, -num)
head(data_3)
##   num key value
## 1   a   A -9.00
## 2   b   A  0.00
## 3   c   A -2.67
## 4   d   A -9.00
## 5   e   A    NA
## 6   f   A -9.00
data_3$num <- factor(data_3$num, levels = unique(labs$label))
#data_3$key <- gsub("\\."," ", data_3$key)
data_3$key <- factor(data_3$key, levels = unique(labs1$label))
#data_3$A
#unique(data_3$key)
p2 <- ggplot() + geom_tile(data = data_3,aes( x = key, 
                                              y= num,
                                              height = 1,
                                              fill = value,
                                              width = 1, colour= ""),size= 0.2) +  
  ylab("") + xlab("") + 
  theme(legend.position = c(1.22,0.81), 
        plot.background = element_rect(fill="green")) +
  scale_y_discrete(expand = c(0, 0),position = "right") +
  scale_x_discrete(expand = c(0, 0)) +
  scale_fill_gradient2(low="blue", high="red", 
                       name = expression('Value'), na.value="gray90") 

p_pvalue <- p2 + guides(colour = guide_legend("Missing value", override.aes = list(fill="gray90"))) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.3, hjust = 1, color = "black")) +
  scale_colour_manual(values= "gray80") + 
  theme(axis.ticks = element_blank(), 
        axis.text.y = element_blank(),
        #panel.background =  element_blank(),
        legend.key.height = unit(0.8,"line"),
        legend.key.width = unit(0.7,"line"))

#theme(panel.background = element_rect(fill = NA, colour = NA),
#                                       plot.background = element_rect(fill = NA,colour = NA))
p_pvalue

##################################################6___MERGE
library(patchwork)
plot_spacer() + p_dendro1 + p_dendro + p_pvalue +  
  plot_layout(widths = c(1,2), 
              heights = c(0.2,2), guides = 'collect')

#################################################################
(plot_spacer() + theme(axis.text = element_blank(), 
                       axis.title = element_blank(), 
                       axis.ticks = element_blank(),
                       plot.margin = unit(c(0,0,0,0), "cm"),
                       plot.background = element_rect(fill="green"))) + 
  (p_dendro1 + theme(axis.text = element_blank(), 
                     axis.title = element_blank(), 
                     axis.ticks.x = element_line(color= "red"),
                     axis.ticks.length.x = unit(2, "mm"),
                     axis.ticks.y = element_blank(),
                     panel.background=element_rect(fill="red"),
                     panel.grid=element_blank(),
                     axis.ticks.length.y = unit(0, "mm"),
                     plot.background = element_rect(fill="green"),
                     plot.margin = unit(c(0,3,0,0), "cm"))) + 
  (p_dendro + theme(axis.text = element_blank(), 
                    axis.title = element_blank(), 
                    axis.ticks = element_blank(),
                    panel.background=element_rect(fill="yellow"),
                    plot.background = element_rect(fill="blue"),
                    panel.grid=element_blank(),
                    plot.margin = unit(c(0,0,0,0), "cm"))) +
  (p_pvalue + theme(axis.text = element_blank(), 
                    axis.title = element_blank(), 
                    axis.ticks = element_blank(),
                    axis.ticks.y = element_blank(),
                    axis.ticks.length.y = unit(0, "mm"),
                    panel.background=element_rect(fill="red"),
                    plot.background = element_rect(fill="green"),
                    plot.margin = unit(c(0,3,0,0), "cm")))  +
  plot_layout(widths = c(1,2), 
              heights = c(0.2,5), guides = 'auto') +
  theme(legend.position=c(1.2,0.85))

####################################################
ggsave(filename = paste0(Sys.Date(),"-plot_dendro_11.tif"), 
       plot = last_plot(), device = "tiff", path = dir_path,
       width = 15, height = 18, units = "cm",
       dpi = 300, limitsize = TRUE)
ggsave(filename = paste0(Sys.Date(),"-plot_hm-dendro_all.pdf"), 
       plot = last_plot(), device = "pdf", path = dir_path,
       width = 16, height = 18, units = "cm",
       dpi = 300, limitsize = TRUE)
###########################################
write.csv(labs, paste0(dir_path,Sys.Date(),"-","labs_order.csv"),row.names = FALSE,na = "")