R/table_freq_cross_weighted_plot.R

Defines functions table.freq.cross.weighted.plot

Documented in table.freq.cross.weighted.plot

#' Cette fonction permet de visualiser les tris croisés
#'
#' @param df output tris croisés
#' @param var liste des variables 
#' @export
#' @examples 
#' lapply(seq_along(df), function(x) {
#'   tryCatch({table.freq.cross.weighted.plot(df, x)},
#'   error = function(cond) return(NA))
#'   })

# Plot 
table.freq.cross.weighted.plot = function(df, var, path){
  # Process for unique cross table
  if (is.data.frame(df)) {
    pl = df[,-ncol(df)] %>%
      as.data.frame() %>%
      rename("id" = 1) %>% 
      tidyr::gather("x", "y",-id) %>%
      rename_all( ~ c("x", "y", "Freq")) %>%
      mutate_at(vars(Freq), as.numeric) %>% 
      ggplot(aes(y,x,fill = Freq)) + 
      geom_tile() + 
      geom_text(aes(label = paste0(round(Freq), "%")), color = "black", size = 4) +
      scale_fill_gradient(low = "white", high = "#A7D7FD", name = "Fréquence") + 
      coord_flip() + 
      theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                       size = 12, hjust = 1),
            axis.title.x = element_blank(),
            axis.title.y = element_blank(),
            panel.grid.major = element_blank(),
            panel.border = element_blank(),
            panel.background = element_blank(),
            axis.ticks = element_blank(),
            plot.caption = element_text(vjust = 0)
      ) +
      labs(caption = paste("Chi2 p-value =", round(as.numeric(df[1, ncol(df)]), 4)))
    
    ggsave(plot = pl, paste0(path, var, ".png"), device = "png", units = "cm", width = 30, height = 25)
    
  }
  
  # Process for multiple cross table
  else {
    pl = df[[var]][,-ncol(df[[var]])] %>%
      as.data.frame() %>%
      rename("id" = 1) %>% 
      tidyr::gather("x", "y",-id) %>%
      rename_all( ~ c("x", "y", "Freq")) %>%
      mutate_at(vars(Freq), as.numeric) %>% 
      ggplot(aes(y,x,fill = Freq)) + 
      geom_tile() + 
      geom_text(aes(label = paste0(round(Freq), "%")), color = "black", size = 4) +
      scale_fill_gradient(low = "white", high = "#A7D7FD", name = "Fréquence") + 
      coord_flip() + 
      theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                       size = 12, hjust = 1),
            axis.title.x = element_blank(),
            axis.title.y = element_blank(),
            panel.grid.major = element_blank(),
            panel.border = element_blank(),
            panel.background = element_blank(),
            axis.ticks = element_blank(),
            plot.caption = element_text(vjust = 0)
      ) +
      labs(caption = paste("Chi2 p-value =",round(as.numeric(df[[var]][1, ncol(df[[var]])]), 4)))
    
    ggsave(plot = pl, paste0(path, names(df[var]), ".png"), device = "png", units = "cm", width = 30, height = 25)
  }
  
  # Return plot
  return(pl)
}
AlexisMayer/toolbox documentation built on Aug. 25, 2020, 3:56 p.m.