问题描述
我有一个图表(下面的简化示例),我想将 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)
)
解决方法
您需要在 axis.text.x.top
中指定正确的元素(现在是 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)
)