r - 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()
,但我的示例只是一个图表。
谢谢
解决方案
有几个解决方案:
@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
我将不得不调整该值以使行距恰到好处,但这会起作用。
推荐阅读
- python - Python 类成员类型提示
- node.js - 使套接字响应为十六进制字节
- laravel - 页面更改后 Laravel 数据表错误
- wordpress - 引导按钮和特定类别的帖子
- angularjs - AngularJS,Karma:无法获得 indexedDB 包装器的承诺解决工作
- java - 如何处理Java中的精确精度?
- php - 如何在mysql存储过程中foreach数组
- amazon-web-services - 无法创建 Spot 实例
- pandas - 用于神经网络的 jupyter notebook、keras、tensorflow 中的 ValueError
- dart - 如何根据颤动中的触摸事件移动custompainter