Multi line title in ggplot 2 with multiple italicized words

后端 未结 3 551
闹比i
闹比i 2020-12-10 04:59

I am trying to create a plot title manually formatted on two lines which includes two italicized words, I have done some s

3条回答
  •  爱一瞬间的悲伤
    2020-12-10 05:03

    We could also call cowplot::draw_label() two times (inspired from this discussion). However, we need to tweak a bit the position and make enough space for the custom title. I gave more explanations about this approach and also using ggplot2::annotation_custom() in ggplot2 two-line label with expression.

    library(ggplot2)
    library(cowplot)
    #> 
    #> Attaching package: 'cowplot'
    #> The following object is masked from 'package:ggplot2':
    #> 
    #>     ggsave
    
    # The two lines we wish on the plot. The ~~ creates extra space between the
    # expression's components, might be needed here.
    line_1 <- expression("First Line of Title with" ~~ italic("Species"))
    line_2 <- expression(italic("Species") ~~ "second line words" ~~ italic("anotherSpecies") ~~ "the end")
    
    # Make enough space for the custom two lines title
    p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
      geom_point() + 
      labs(title = "") + # empty title
      # Force a wider top margin to make enough space
      theme(plot.title = element_text(size = 10, # also adjust text size if needed
                                      margin = margin(t = 10, r = 0, b = 0, l = 0,
                                                      unit = "mm")))
    
    # Call cowplot::draw_label two times to plot the two lines of text
    ggdraw(p) +
      draw_label(line_1, x = 0.55, y = 0.97) +
      draw_label(line_2, x = 0.55, y = 0.93)
    

    Created on 2019-01-14 by the reprex package (v0.2.1)

提交回复
热议问题