Search code examples
rggplot2axis-labels

ggplot2 axis label spacing when using two rows


When I run the following ggplot2 code, I get some odd spacing in my axis label (e.g., on the second row, it's as if ggplot2 tries to center the units, but then leaves the parentheses very far apart).

x <- c("x", "y")
y <- c(5, 10)
df <- data.frame(x, y)

ggplot(df, aes(x = x, y = y)) +
  ylab(bquote('Mean Subscribers\n('*km^2*')'))

[![enter image description here][1]][1]

Any idea how I remove the space and center the axis label? [1]: https://i.sstatic.net/0fr7R.png


Solution

  • An alternative solution to using bquote() is to use {ggtext} which lets you use markdown syntax. I've found it much more straightforward to use, and much better at multi-line labels. For example:

    library(ggtext)
    ggplot(df, aes(x = x, y = y)) +
      ylab('Mean Subscribers<br>(km<sup>2</sup>)') +
      theme(axis.title.y = element_markdown())
    

    chart