- ggcorrplot<-function(df, var, value,color="#FFFFFF00", stat="signif", tri="all", method="pearson"){
- allnames<-colnames(df)
- m.df<-df %>% spread(all_of(var), all_of(value)) %>% select(!any_of(allnames))
- mcor<-cor(m.df, m.df, use="pairwise.complete.obs", method = method) # Por defecto usa el método de Pearson.
- mpval<-Hmisc::rcorr(as.matrix(m.df), type=method)$P
-
- order<- mcor %>% as.data.frame() %>% add_column(Var1=rownames(mcor),.before=1) %>% clustsort
-
- mcor<-mcor[order$y, order$x]
- mpval<-mpval[order$y, order$x]
-
- df<-mcor %>% as.data.frame()
- if (tri == "upper"){
- df[lower.tri(df, diag=F)]<-NA
- }
- if (tri == "lower"){
- df[upper.tri(df, diag=F)]<-NA
- }
- df<-df %>% add_column(Var1=rownames(mcor),.before=1) %>%
- gather(Var2, Value, -Var1) %>% filter(!is.na(Value))
-
- df.pval<-mpval %>% as.data.frame()
- if (tri == "upper"){
- df.pval[lower.tri(df.pval, diag=F)]<-NA
- }
- if (tri == "lower"){
- df.pval[upper.tri(df.pval, diag=F)]<-NA
- }
- df.pval<-df.pval %>% add_column(Var1=rownames(mpval),.before=1) %>%
- gather(Var2, Value, -Var1) %>% filter(!is.na(Value))
-
- df.pval$Value<-round(df.pval$Value, 3)
- if (!stat %in% c("signif","none","pval")){stat<-"signif"}
- if (stat=="signif"){
- df.pval$Value<-gtools::stars.pval(df.pval$Value)
- }
- if (stat=="none"){
- df.pval$Value<-""
- }
-
-
- df$Var1<-factor(df$Var1, levels=order$x)
- df$Var2<-factor(df$Var2, levels=order$y)
-
- ggplot(df, aes(Var1, Var2))+
- geom_tile(aes(fill=Value), color=color)+
- geom_text(data=df.pval, aes(label=Value), color="white")+
- scale_fill_gradientn(colors=col2(200))+
- theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5),
- panel.background = element_blank(),
- axis.ticks = element_blank())
- }
|