Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi line title in ggplot 2 with multiple italicized words

Tags:

plot

r

ggplot2

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

like image 823
Arch Avatar asked Nov 21 '16 12:11

Arch


2 Answers

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

Using scriptstyle is not a necessity, but imho it is nicer to have your subtitle in a smaller font than the main title.

See also ?plotmath for other usefull customizations.

like image 76
Jaap Avatar answered Sep 19 '22 18:09

Jaap


As an alternative to inserting line breaks in title, you may use title together with subtitle (available from ggplot 2.2.0). Possibly this makes the plothmathing slightly more straightforward.

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  labs(title = expression("First line: "*italic("Honorificabilitudinitatibus")),
       subtitle = expression("Second line: "*italic("Honorificabilitudinitatibus praelongus")*" and more"))
p

enter image description here


If you wish the font size to be the same on both lines, set the desired size in theme.

p + theme(plot.title = element_text(size = 12),
          plot.subtitle = element_text(size = 12))

Note that both title and subtitle are left-aligned by default in ggplot2 2.2.0. The text can be centered by adding hjust = 0.5 to element_text above.

like image 39
Henrik Avatar answered Sep 18 '22 18:09

Henrik