I am trying to produce two lines in a y axis label in ggplot in R, where the second line has some relatively complex text that seems to make it difficult to print on two lines.
On a single line, I have gotten this script to print just fine using bquote:
Figure 1:
ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() +
ylab(bquote('Efflux ('*mu~ 'mol' ~CO[2]~ m^-2~s^-1*')'))
And, with relatively simple text, I can use the \n feature within ylab to produce two lines:
Figure 2:
ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() +
ylab("Efflux \n Carbon Dioxide")
However, trying to use the atop feature within bquote, I have struggled to figure out how to use commas, quotations marks etc. to properly print these two lines of y axis labels:
ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() +
ylab(bquote(atop("Efflux", ('*mu~ 'mol' ~CO[2]~ m^-2~s^-1*'))))
This prints an error, which I know has to do with placement of quotation marks. Does anyone have a lead on how to print this more complex text over two lines?
You could try using element_markdown
from the ggtext
package. This allows you to use markdown (or html) to produce the line breaks, symbols, subscripts and superscripts you need without resorting to bquote
, which struggles with multi-line inputs. You can even show the units in italics, as in this example:
library(ggplot2)
library(ggtext)
ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) +
geom_point() +
ylab("Efflux<br><i>(μmol CO<sub>2</sub> m<sup>-2</sup>s<sup>-1</sup>)</i>") +
theme(axis.title.y = element_markdown())