Left-adjust title in ggplot2, or absolute position for ggtitle

前端 未结 5 1708
广开言路
广开言路 2020-12-02 23:16

I would like to left align the title in a plot like this

ggplot(data = economics, aes(x = date, y = unemploy)) +
 geom_line() +
 ggtitle(\"Unemployment in US         


        
5条回答
  •  渐次进展
    2020-12-02 23:36

    You can manually adjust the layout of the ggplot output. First, we set up the basic plot:

    library(ggplot2)
    p <- ggplot(data = economics, aes(x = date, y = unemploy)) +
     geom_line() +
     labs(title = "Unemployment in USA between 1967 and 2007", 
          x = NULL, y = "Unemployed [thousands]")
    

    We can now convert the ggplot object into a gtable object, and inspect the layout of the elements in the plot. Notice that the title is in the fourth column of the grid, the same column as the main panel.

    g <- ggplotGrob(p)
    g$layout
    #    t l  b r  z clip       name
    # 17 1 1 10 7  0   on background
    # 1  5 3  5 3  5  off     spacer
    # 2  6 3  6 3  7  off     axis-l
    # 3  7 3  7 3  3  off     spacer
    # 4  5 4  5 4  6  off     axis-t
    # 5  6 4  6 4  1   on      panel
    # 6  7 4  7 4  9  off     axis-b
    # 7  5 5  5 5  4  off     spacer
    # 8  6 5  6 5  8  off     axis-r
    # 9  7 5  7 5  2  off     spacer
    # 10 4 4  4 4 10  off     xlab-t
    # 11 8 4  8 4 11  off     xlab-b
    # 12 6 2  6 2 12  off     ylab-l
    # 13 6 6  6 6 13  off     ylab-r
    # 14 3 4  3 4 14  off   subtitle
    # 15 2 4  2 4 15  off      title
    # 16 9 4  9 4 16  off    caption
    

    To align the title with the left edge of the plot, we can change the l value to 1.

    g$layout$l[g$layout$name == "title"] <- 1
    

    Draw the modified grid:

    grid::grid.draw(g)
    

    Result:

提交回复
热议问题