Reppo for internal functions.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.7 KiB

  1. ggcorrplot<-function(df, var, value,color="#FFFFFF00", stat="signif", tri="all", method="pearson"){
  2. allnames<-colnames(df)
  3. m.df<-df %>% spread(all_of(var), all_of(value)) %>% select(!any_of(allnames))
  4. mcor<-cor(m.df, m.df, use="pairwise.complete.obs", method = method) # Por defecto usa el método de Pearson.
  5. mpval<-Hmisc::rcorr(as.matrix(m.df), type=method)$P
  6. order<- mcor %>% as.data.frame() %>% add_column(Var1=rownames(mcor),.before=1) %>% clustsort
  7. mcor<-mcor[order$y, order$x]
  8. mpval<-mpval[order$y, order$x]
  9. df<-mcor %>% as.data.frame()
  10. if (tri == "upper"){
  11. df[lower.tri(df, diag=F)]<-NA
  12. }
  13. if (tri == "lower"){
  14. df[upper.tri(df, diag=F)]<-NA
  15. }
  16. df<-df %>% add_column(Var1=rownames(mcor),.before=1) %>%
  17. gather(Var2, Value, -Var1) %>% filter(!is.na(Value))
  18. df.pval<-mpval %>% as.data.frame()
  19. if (tri == "upper"){
  20. df.pval[lower.tri(df.pval, diag=F)]<-NA
  21. }
  22. if (tri == "lower"){
  23. df.pval[upper.tri(df.pval, diag=F)]<-NA
  24. }
  25. df.pval<-df.pval %>% add_column(Var1=rownames(mpval),.before=1) %>%
  26. gather(Var2, Value, -Var1) %>% filter(!is.na(Value))
  27. df.pval$Value<-round(df.pval$Value, 3)
  28. if (!stat %in% c("signif","none","pval")){stat<-"signif"}
  29. if (stat=="signif"){
  30. df.pval$Value<-gtools::stars.pval(df.pval$Value)
  31. }
  32. if (stat=="none"){
  33. df.pval$Value<-""
  34. }
  35. df$Var1<-factor(df$Var1, levels=order$x)
  36. df$Var2<-factor(df$Var2, levels=order$y)
  37. ggplot(df, aes(Var1, Var2))+
  38. geom_tile(aes(fill=Value), color=color)+
  39. geom_text(data=df.pval, aes(label=Value), color="white")+
  40. scale_fill_gradientn(colors=col2(200))+
  41. theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5),
  42. panel.background = element_blank(),
  43. axis.ticks = element_blank())
  44. }