Adjust title vertically to inside the plot - vjust not working

后端 未结 1 1765
情歌与酒
情歌与酒 2021-01-05 00:27

I want to place the title inside the plot instead at the default top position. Here is a simple code snippet

library(ggplot2)
df <- data.frame(x = c(1:10)         


        
相关标签:
1条回答
  • 2021-01-05 01:12

    In the ggplot issue "vjust not working in v 2.0 for plot.title?", Hadley writes:

    "All text elements now have a margin, which by default scale with the font size in the theme. This leads to nicer spacing, particularly at large font sizes. This means hacks with vjust and hjust no longer work. Instead, use the margin() parameter of element_text()"

    Play around with the t and b arguments in margin to adjust the title, e.g.:

    ggplot(df, aes(x, y))+
      geom_line() +
      ggtitle("Demo") + 
        theme(plot.title = element_text(margin = margin(t = 10, b = -20)))
    

    See ?margin for further arguments.


    Note that you should use the margin argument for axis.title.x and axis.title.y as well:

    ggplot() + ggtitle("this is title") + xlab("this is x") + ylab("this is y") + 
      theme(plot.title = element_text(margin = margin(b = -10)),
            axis.title.x = element_text(margin = margin(t = -10)),
            axis.title.y = element_text(margin = margin(r = -10)))
    

    0 讨论(0)
提交回复
热议问题