Search code examples
rggplot2ggtext

ggtext : element_markdown not working with position = "top"


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)
  )

Solution

  • 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)
        )