2

I have a chart (simplified example below) where I want to put the x-axis at the top. The labels use element_markdown to include line breaks.

It all works fine until I add position = "top" which seems to stop the line break being applied. Do you know why?

This is how its supposed to look

enter image description here

And the code with position = "top" commented out.

library(tidyverse, ggtext)

periods <-c(1,2,3)
periodLabels <- c("Jan", "Feb<br>21", "Mar")
data <- data.frame(period = periods,
                   y = c(10, 20, 30))
ggplot(data, aes(period, y)) +
  geom_tile() +
  coord_cartesian(expand = FALSE) +
  # scales
  scale_x_continuous(breaks = periods,
                     labels = periodLabels#,
                     #position = "top"
  ) +
  theme_minimal(base_size = 5) +
  theme(
    axis.text.x = element_markdown(size = 8, lineheight = 1.05)
  )
Chris
  • 1,449
  • 1
  • 18
  • 39

1 Answers1

3

You need to specify the correct element (axis.text.x.top now) in theme:

periods <-c(1,2,3)
periodLabels <- c("Jan", "Feb<br>21", "Mar")
data <- data.frame(period = periods,
                   y = c(10, 20, 30))
ggplot(data, aes(period, y)) +
    geom_tile() +
    coord_cartesian(expand = FALSE) +
    # scales
    scale_x_continuous(breaks = periods,
                       labels = periodLabels,
                       position = "top"
    ) +
    theme_minimal(base_size = 5) +
    theme(
        axis.text.x.top = element_markdown(size = 8, lineheight = 1.05)
    )

Alex
  • 474
  • 4
  • 12
  • Thanks Alex, that will work for me. It would be great if anyone knows why. Does ggtext get switched off? – Chris May 09 '21 at 13:11
  • Seems to be a known issue: You need to change the element in theme (https://github.com/wilkelab/ggtext/issues/5). I edited the answer – Alex May 09 '21 at 13:49