(This is my first question on this forum, sorry in advance if it's not that clear!)
I am trying to rename the labels of the x axis of a graph made with ggplot2 in a way that:
- it appears on two lines, and
- some of the characters are in italic.
I have found two answers to help me with this problem, the first regarding italic in titles (How to italicize part (one or two words) of an axis title), the second regarding writing titles on two lines (Add line break to axis labels and ticks in ggplot).
Unfortunetaly, when I try those two solutions together, it doesn't work.
My case is a bit complex, so let me show you a simple analogous example, using the mtcars dataset.
Here's the base code:
base <- mtcars %>% ggplot(aes(x = factor(cyl))) +
geom_bar() +
scale_y_continuous(breaks = 0:20) +
xlab(NULL)
base
Which gives this: Base graph
What I want is this (I completed it in Paint): Desired graph
The best I can do, based on my findings, is this:
addline_format <- function(x,...){
gsub('\\s','\n',x)
}
my_x_titles <- c(expression(paste("4 cylinders (", italic("N"), " = 11)")),
expression(paste("6 cylinders (", italic("N"), " = 7)")),
expression(paste("8 cylinders (", italic("N"), " = 14)")))
base + scale_x_discrete(breaks = c(4, 6, 8),
labels = addline_format(my_x_titles))
Which gives something not great: My not-great solution
Using the homemade addline_format function seems to block the effect the italic function. Moreover, I'd like the labels to be on only two lines (please refer to my Desired solution picture), not multiple, even though I use multiple spaces.
Anyone would know how to solve this?