Home > front end >  How to turn a contingency table directly into a bar graph when using the base table function?
How to turn a contingency table directly into a bar graph when using the base table function?

Time:03-21

Original DataInput

Desired Output

I am attempting to create a bar graph directly from a contingency table but I do not know of a function in ggplot2 that has such capability. My original data looks like this with 0s, 1s, and -1s representing categorical answers in the columns. The problem is that I do not know how to subgroup them by the unique values in each of the columns.

I am iterating across columns using this code and this is what I have so far.

for (x in colnames(df)){

bar_graph <- ggplot(df, aes(x = Variant, y=x, fill = df[[x]])) geom_bar(stat = "identity",position = "dodge")

}

CodePudding user response:

You may wish to create a separate table. Extract the legend as a separate grob then lay out each part separately.

Sample code:

    library(grid)
    library(gridExtra)
    library(ggplot2)

  df1<-df %>%
      gather(name, value, `Yes`:`No`)   
    
    df1$name=factor(df1$name, levels=c("Yes", "No"))
      
      g_legend <- function(a.gplot){
        tmp <- ggplot_gtable(ggplot_build(a.gplot))
        leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
        legend <- tmp$grobs[[leg]]
        return(legend)}
    
    p = ggplot(df1, aes(x=variable, y=value, fill=name) )   
      geom_bar(stat="identity", position="dodge")  
      theme_bw() 
      theme(axis.text.x = element_text(hjust = 1, face="bold", size=12, color="black"), 
            axis.title.x = element_blank(),
            axis.text.y = element_text( face="bold", size=12, color="black"),
            axis.title.y = element_blank(),
            strip.text = element_text(size=10, face="bold"),
            legend.position = "none",
            legend.title = element_blank(),
            legend.text = element_text(color = "black", size = 16,face="bold")) 
            scale_y_continuous(expand = expansion(mult = c(0, .1))) 
    ggtitle("Relationship between daily consumption of fruit/fruit juice and SNP AX")
    
    
    
    leg = g_legend(p)
    
    
    tab = t(df)
    tab = tableGrob(tab, rows=NULL, theme=ttheme_minimal(base_size = 16))
    tab$widths <- unit(rep(1/ncol(tab), ncol(tab)), "npc")
    
    grid.arrange(arrangeGrob(nullGrob(), 
                             p    
                               theme(axis.text.x=element_blank(),
                                     axis.title.x=element_blank(),
                                     axis.ticks.x=element_blank()),
                             widths=c(1,8)), 
                arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)),
                                                    tab, nullGrob(), widths=c(6,20,1)), heights=c(4,1))
      
      

Plot:

enter image description here Sample data:

df<-structure(list(variable = c("AA", "AB", "BB"), Yes = c(10, 50, 
90), No = c(80, 40, 10)), spec = structure(list(cols = list(variable = structure(list(), class = c("collector_character", 
"collector")), Yes = structure(list(), class = c("collector_double", 
"collector")), No = structure(list(), class = c("collector_double", 
"collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"), row.names = c(NA, 
-3L), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"))


df1<-structure(list(variable = c("AA", "AB", "BB", "AA", "AB", "BB"
), name = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Yes", 
"No"), class = "factor"), value = c(10, 50, 90, 80, 40, 10)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))
  • Related