Multirow axis labels with nested grouping variables

前端 未结 6 2011
后悔当初
后悔当初 2020-11-22 16:42

I would like the levels of two different nested grouping variables to appear on separate lines below the plot, and not in the legend. What I have right now is this code:

6条回答
  •  醉梦人生
    2020-11-22 17:17

    An alternative to agstudy's method is to edit the gtable and insert an "axis" calculated by ggplot2,

    p <- ggplot(data=data, aes(x=Category, y=Value, fill=Group)) + 
      geom_bar(position = position_dodge(width=0.9),stat='identity') +
      geom_text(aes(label=paste(Value, "%")),
                position=position_dodge(width=0.9), vjust=-0.25)
    
    axis <- ggplot(data=data, aes(x=Category, y=Value, colour=Group)) +
      geom_text(aes(label=Group, y=0),
                position=position_dodge(width=0.9))
    
    annotation <- gtable_filter(ggplotGrob(axis), "panel", trim=TRUE)
    annotation[["grobs"]][[1]][["children"]][c(1,3)] <- NULL #only keep textGrob
    
    library(gtable)
    g <- ggplotGrob(p)
    gtable_add_grobs <- gtable_add_grob # let's use this alias
    g <- gtable_add_rows(g, unit(1,"line"), pos=4)
    g <- gtable_add_grobs(g, annotation, t=5, b=5, l=4, r=4)
    grid.newpage()
    grid.draw(g)
    

    enter image description here

提交回复
热议问题