首页 > 解决方案 > R:如何让 ggplot2::geom_text() 与其他格式化文本一起插入换行符?

问题描述

我正在尝试使用此问题的最佳答案中描述的方法将注释放在多面箱线图中:Annotating text on individual facet in ggplot2

并使用此处选择的方法格式化文本:https ://ggplot2.tidyverse.org/reference/annotate.html

我似乎无法弄清楚为什么geom_text()不在我的代码中插入换行符的地方\n。这是一个简化版本:

p.data <- data.frame(Main = rep("Ratio", 100),
                     CAT = c('A','B','C','D'),
                     value = rnorm(100, mean = 1.5, sd = 1.5))
p.text <- data.frame(Main = "Ratio",
                     CAT = 'B',
                     value = 7,
                     lab = "Text")
p <-  ggplot(data = p.data, aes(x = CAT, y = value, fill = CAT)) +
      geom_boxplot() +
      scale_y_continuous(breaks = c(0:6), limits = c(0,8)) +
      facet_wrap(~ Main, scales = 'fixed', nrow = 1, ncol = 1) +
      geom_text(data = p.text, hjust = 0, parse = TRUE,
                label = "paste(bold(CMV): f ^ 2, \" = 0.04, p = 0.003\", \n bold(MDD): n.s.)")
p

在此处输入图像描述

在其他一些废话中,我尝试过:

label = "paste(bold(CMV): f ^ 2, \" = 0.04, p = 0.003\", \n bold(MDD): n.s.)"
label = "paste(bold(CMV): f ^ 2, \" = 0.04, p = 0.003\", \n, bold(MDD): n.s.)"
label = "paste(bold(CMV): f ^ 2, \" = 0.04, p = 0.003\", \"\n\", bold(MDD): n.s.)"
label = "paste(bold(CMV): f ^ 2, \" = 0.04, p = 0.003\", \"\n bold(MDD): n.s.\")"
label = "paste(bold(CMV): f ^ 2, \" = 0.04, p = 0.003\"\n, bold(MDD): n.s.)"

...但没有任何效果。

如果不是很明显,我想要的是一行的 CMV 结果和另一行的 MDD 结果,同时保持粗体字体和上标“2”。我的最终图表将由一个带有一个面的图表和一个带有三个面的使用 粘在一起的图表组成grid.arrange(),但我的示例只是一个图表。

谢谢

标签: rggplot2boxplotquotesgeom-text

解决方案


有几个解决方案:

@eipi10 在上面的评论中建议使用atop()

p.data <- data.frame(Main = rep("Ratio", 100),
                 CAT = c('A','B','C','D'),
                 value = rnorm(100, mean = 1.5, sd = 1.5))
p.text <- data.frame(Main = "Ratio",
                 CAT = 'B',
                 value = 7,
                 lab = "Text")
p <- ggplot(data = p.data, aes(x = CAT, y = value, fill = CAT)) +
     geom_boxplot() +
     scale_y_continuous(breaks = c(0:6), limits = c(0,8)) +
     facet_wrap(~ Main, scales = 'fixed', nrow = 1, ncol = 1) +
     geom_text(data = p.text, hjust = 0, parse = TRUE,
               label = "atop(paste(bold(CMV): f ^ 2, \" = 0.04, p = 0.003\"), 
                             bold(MDD): n.s.)")
p

在此处输入图像描述

但是,我对格式很挑剔,希望两行都左对齐。因此,我将在p.text数据框中创建另一行,并以较低的值放置另一行geom_text

p.text <- data.frame(Main = "Ratio",
                     CAT = 'B',
                     value = c(7, 6),
                     lab = "Text")
p <- ggplot(data = p.data, aes(x = CAT, y = value, fill = CAT)) +
  geom_boxplot() +
  scale_y_continuous(breaks = c(0:6), limits = c(0,8)) +
  facet_wrap(~ Main, scales = 'fixed', nrow = 1, ncol = 1) +
  geom_text(data = p.text[1,], hjust = 0, parse = TRUE,
            label = "paste(bold(CMV): f ^ 2, \" = 0.04, p = 0.003\")") +
  geom_text(data = p.text[2,], hjust = 0, parse = TRUE,
            label = "paste(bold(MDD): n.s.)")
p

在此处输入图像描述

我将不得不调整该值以使行距恰到好处,但这会起作用。


推荐阅读