0

(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:

  1. it appears on two lines, and
  2. 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?

Simon
  • 1
  • 4
  • https://github.com/clauswilke/ggtext – Axeman Sep 03 '19 at 20:18
  • 1
    I think package **ggtext** will make all of this much easier, but in the past the answer for italicized text plus line breaks has been to use `atop()`. It works, but not always exactly how we want it to. See some examples [here](https://stackoverflow.com/questions/40720387/multi-line-title-in-ggplot-2-with-multiple-italicized-words/40720451#40720451) and [here](https://stackoverflow.com/questions/16490331/combining-new-lines-and-italics-in-facet-labels-with-ggplot2) – aosmith Sep 03 '19 at 20:23

1 Answers1

0

You can cheat using atop:

my_x_titles <- c(
  expression(atop(paste("4 cylinders"), (italic(N) == 11))),
  expression(atop(paste("6 cylinders"), (italic(N) == 7))),
  expression(atop(paste("8 cylinders"), (italic(N) == 14)))
)

base + scale_x_discrete(breaks = c(4, 6, 8),
                        labels = my_x_titles)
Axeman
  • 32,068
  • 8
  • 81
  • 94