Arch Arch - 16 days ago 12
R Question

Multi line title in ggplot 2 with multiple italicized words

I am trying to create a plot title manually formatted on two lines which includes two italicized words, I have done some searching
on Stack Exchange but have not found a good solution to this seemingly simple problem.

The scientific names of the two species are fairly long, and thus the need for a multi-line title (ggplot2 doesn't format this).

Objective:


..........First Line of Title with Species

Second line words anotherItalicSpecies the end


ggplot(mtcars,aes(x=wt,y=mpg))+
geom_point()+
labs(title= expression(paste(atop("First line of title with ", atop((italic("Species")))),"
secondline words", italic("anotherSpecies"), "the end")))


Which yields the following mangled title:

enter image description here

Answer

Using a combination of atop, paste, italic and scriptstyle:

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  labs(title = ~ atop(paste('First line of title with ',italic("Species")),
                      paste(scriptstyle(italic("Species")),
                            scriptstyle(" secondline words "),
                            scriptstyle(italic("anotherSpecies")),
                            scriptstyle(" the end"))))

gives you the desired result:

enter image description here

See also ?plotmath for other usefull customizations.