Add secondary X axis labels to ggplot with one X axis

后端 未结 3 1675
囚心锁ツ
囚心锁ツ 2020-12-03 16:16

**Edit, there are two great solutions here, one is marked as the answer, but @hrbrmstr provides a great solution combining two ggplots which works well for this simple plot.

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 16:54

    I think this does what you're looking for:

    library(ggplot2)
    library(grid)
    library(gtable)
    library(gridExtra)
    
    breaks.major <- c(0, 15, 37.5, 52.5, 67.5, 82.5, 95, 100)
    breaks.minor <- c(30, 45, 60, 75, 90)
    labels.minor <- c("", "Extremely\nDissatisfied", "Dissatisfied", "Uncertain",
                      "Satisfied", "Very\nSatisfied", "Extremely\nSatisfied", "")
    lims <- c(0, 100)
    
    # build the main plot with the text axis
    gg1 <- ggplot(mpg, aes(class))
    gg1 <- gg1 + geom_bar()
    gg1 <- gg1 + scale_y_continuous(expand=c(0,0), limit=lims, 
                                    minor_breaks=breaks.minor, 
                                    breaks=breaks.major,
                                    labels=labels.minor)
    gg1 <- gg1 + coord_flip()
    gg1 <- gg1 + theme(panel.grid.major.x=element_blank())
    gg1 <- gg1 + theme(panel.grid.major.y=element_blank())
    gg1 <- gg1 + theme(axis.ticks.x=element_blank())
    gg1 <- gg1 + theme(axis.title=element_blank())
    
    # let ggplot2 do the work of building the second axis
    gg2 <- ggplot(mpg, aes(class))
    gg2 <- gg2 + scale_y_continuous(expand=c(0,0), limit=lims, 
                                    breaks=c(0, breaks.minor, 100))
    gg2 <- gg2 + coord_flip()
    gg2 <- gg2 + theme(axis.ticks.x=element_blank())
    gg2 <- gg2 + theme(axis.text.x=element_text(hjust=c(0, 0.5, 0.5, 0.5, 0.5, 0.5, 1)))
    
    gt1 <- ggplot_gtable(ggplot_build(gg1))
    gt2 <- ggplot_gtable(ggplot_build(gg2))
    axis2 <- grid.arrange(gt2$grobs[[5]])
    
    gt <- gtable_add_rows(gt1, unit(0.1, "null"), 4)
    grid.arrange(gtable_add_grob(gt, axis2, t=5, l=4, b=5, r=4))
    

提交回复
热议问题