Aligning title, subtitle and caption for horizontal ggplot barchart

前端 未结 2 548
眼角桃花
眼角桃花 2021-02-05 08:29

I would like to left align the plot.title, plot.subtitle and plot.caption in a horizontal ggplot2 barchart.

Example:

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 08:54

    While you could edit those three grobs, you can also just:

    library(gridExtra)
    library(grid)
    
    grid.arrange(
      textGrob("This is a nice title", 
               gp=gpar(fontsize=16, col="#2b2b2b"), 
               x=unit(0.005, "npc"), just=c("left", "bottom")),
      textGrob("A subtitle",  
               gp=gpar(fontsize=12, col="#2b2b2b"), 
               x=unit(0.005, "npc"), just=c("left", "bottom")),
      ggplot(df, aes(x=type, y=value)) +
        geom_bar(stat='identity') +
        coord_flip() +
        theme(axis.title=element_blank()),
      textGrob("We even have a caption. A very long one indeed.", 
               gp=gpar(fontsize=9, col="#2b2b2b"), 
               x=unit(0.005, "npc"), just=c("left", "bottom")),
      ncol=1,
      heights=c(0.075, 0.025, 0.85, 0.05)
    )
    

    Make a wrapper for it, put it in a personal pkg. Boom. Done.


    library(ggplot2)
    library(gridExtra)
    library(grid)
    
    df <- data.frame(type=factor(c("Brooklyn","Manhatten and\n Queens")), value=c(15,30))
    
    ggplot(df, aes(x=type, y=value)) +
      geom_bar(stat='identity') +
      coord_flip() +
      theme(axis.title=element_blank()) +
      theme(plot.margin=margin(l=0, t=5, b=5))-> gg
    
    flush_plot <- function(x, title, subtitle, caption) {
      tg <- function(label, ...) {
        textGrob(label,  x=unit(0, "npc"), just=c("left", "bottom"),
                 gp=do.call(gpar, as.list(substitute(list(...)))[-1L])) }
      grid.arrange(
        tg(title, fontsize=16, col="#2b2b2b"),
        tg(subtitle, fontsize=12, col="#2b2b2b"), x,
        tg(caption, fontsize=9, col="#2b2b2b"),
        ncol=1, heights=c(0.075, 0.025, 0.85, 0.05)
      )
    }
    
    flush_plot(gg, "This is a nice title", "A subtitle", 
               "We even have a caption. A very long one indeed.")
    

提交回复
热议问题