How to plot x-axis labels and bars between tick marks in ggplot2 bar plot?

后端 未结 2 2013
情书的邮戳
情书的邮戳 2021-01-11 12:17

I prepared a MWE and hope for help on how to set ticks and labels at different position on the x-axis for a grouped bar plot.

library(ggplot2)
library(reshap         


        
2条回答
  •  温柔的废话
    2021-01-11 12:51

    Here is another solution which uses grid package.

    library(grid)
    
    nTicks <- 2
    tickersPosition <- unit(rep(1:nTicks /(nTicks+1), each=2), "native")
    

    Part 1:nTicks /(nTicks+1) identifies positions where ticks will be placed.

    p1 <- ggplot(data, aes(name,value)) +
      geom_bar(aes(fill = variable), position = "dodge", stat = "identity") 
    

    To change position of ticks we need to create gtable

    p2 <- ggplot_gtable(ggplot_build(p1))
    

    and find the right grob (using str):

    p2$grobs[[7]]$children$axis$grobs[[1]]$x <- tickersPosition
    

    After the position is rewritten, we can run

    grid::grid.draw(p2)
    

    which will show warnings. This is because of a different number of splits.

提交回复
热议问题