Aligning title, subtitle and caption for horizontal ggplot barchart

前端 未结 2 547
眼角桃花
眼角桃花 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:58

    This question refers to this github tidyverse/ggplot2 solved issue: https://github.com/tidyverse/ggplot2/issues/3252

    And it is implemented in ggplot2 (development version): https://github.com/tidyverse/ggplot2/blob/15263f7580d6b5100989f7c1da5d2f5255e480f9/NEWS.md

    Themes have gained two new parameters, plot.title.position and plot.caption.position, that can be used to customize how plot title/subtitle and plot caption are positioned relative to the overall plot (@clauswilke, #3252).

    To follow your example as a reprex:

    # First install the development version from GitHub:
    #install.packages("devtools") #If required
    #devtools::install_github("tidyverse/ggplot2")
    
    library(ggplot2)
    packageVersion("ggplot2")
    #> [1] '3.2.1.9000'
    
    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() +
      labs(title = "This is a nice title",
           subtitle = "A subtitle",
           caption  = "We even have a caption. A very long one indeed.") +
      theme(plot.caption = element_text(hjust = 0, face= "italic"), #Default is hjust=1
            plot.title.position = "plot", #NEW parameter. Apply for subtitle too.
            plot.caption.position =  "plot") #NEW parameter
    

    Created on 2019-09-04 by the reprex package (v0.3.0)

提交回复
热议问题