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.

73 lines
2.5 KiB

  1. ggheatmap<-function(df, x=NULL, y=NULL, value=NULL, grouping="mean", exclude_group=NULL, scale="none",color="#FFFFFF00"){
  2. if (is.null(x)){x=colnames(df)[1]}
  3. if (is.null(y)){y=colnames(df)[2]}
  4. if (is.null(value)){value=colnames(df)[3]}
  5. df<-rename(df, "VarX"=all_of(x), "VarY"=all_of(y), "Value"=all_of(value))
  6. if (is.null(exclude_group)){
  7. df<-df %>% group_by(VarX,VarY)
  8. }else{
  9. df<-df %>% group_by_("VarX","VarY",exclude_group) #%>% rename(exclude_group="all_of(exclude_group)")
  10. }
  11. if (grouping == "mean"){
  12. df<-df %>% summarise(Value=mean(Value)) %>% ungroup
  13. }
  14. if (grouping == "median"){
  15. df<-df %>% summarise(Value=median(Value)) %>% ungroup
  16. }
  17. if (length(unique(df$VarX)) > 1 & length(unique(df$VarY)) >
  18. 1) {
  19. order <- clustsort(df %>% spread(VarY, Value) %>% select(!all_of(exclude_group)) %>%
  20. as.data.frame)
  21. }
  22. else {
  23. order <- list()
  24. if (length(unique(df$VarX)) > 1) {
  25. xhclust <- df %>% spread(VarY, Value) %>%
  26. select(!all_of(exclude_group)) %>% as.data.frame
  27. order[["x"]] <- pull(xhclust, 1)[hclust(dist(xhclust %>%
  28. select(-1)))$order]
  29. }
  30. else {
  31. order[["x"]] <- df %>% pull(VarX) %>% unique
  32. }
  33. if (length(unique(df$VarY)) > 1) {
  34. yhclust <- clustsort(df %>% spread(VarY, Value) %>%
  35. select(!all_of(exclude_group)) %>% as.data.frame)
  36. order[["y"]] <- colnames(yhclust)[2:ncol(yhclust)][hclust(dist(t(yhclust %>%
  37. select(-1))))$order]
  38. }
  39. else {
  40. order[["y"]] <- df %>% pull(VarY) %>% unique
  41. }
  42. }
  43. if (scale != "none"){
  44. if (scale == "rows"){
  45. cols<-unique(df$VarY)
  46. sca.df<-spread(df, VarY, Value)
  47. for (i in cols){sca.df[,i]<-scale(sca.df[,i])}
  48. df<-gather(sca.df, VarY, Value, all_of(cols))
  49. }
  50. if (scale == "cols"){
  51. cols<-unique(df$VarX)
  52. sca.df<-spread(df, VarX, Value)
  53. for (i in cols){sca.df[,i]<-scale(sca.df[,i])}
  54. df<-gather(sca.df, VarX, Value, all_of(cols))
  55. }
  56. }
  57. df$VarX<-factor(df$VarX, levels=order$x)
  58. df$VarY<-factor(df$VarY, levels=order$y)
  59. df %>%
  60. ggplot(aes(VarX, VarY, fill=Value))+
  61. labs(x=x, y=y)+
  62. geom_tile(aes(fill=Value), color=color)+
  63. scale_fill_gradientn(colors=col2(200))+
  64. theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5),
  65. panel.background = element_blank(),
  66. axis.ticks = element_blank())
  67. }