ggtext : element_markdown 不适用于 position = "top"

ggtext : element_markdown not working with position = "top"

我有一个图表(下面的简化示例),我想将 x 轴放在顶部。标签使用 element_markdown 来包含换行符。

一切正常,直到我添加 position = "top" 似乎停止应用换行符。你知道为什么吗?

这是它应该的样子

并将 position = "top" 的代码注释掉。

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

您需要在 theme:

中指定正确的元素(axis.text.x.top 现在)
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)
    )