如何进出paste以支持换行符 (\n) parse?annotateggplot2
我正在尝试使用包中的ggplot2NMDS 分析的应力图进行重现,这是我的 MWE,后面是结果图。metaMDSvegan.
library(ggplot2)
library(tibble)
library(vegan)
set.seed(42) # for reproducibility
data(dune)
fit <- metaMDS(dune)
tib <- tibble(fit$diss, fit$dist, fit$dhat)
colnames(tib) <- c("diss", "dist", "dhat")
stress <- fit$stress
coord_x <- min(tib$diss)
coord_y <- max(tib$dist)
nonmetric_r2 <- round(1 - stress * stress, digits = 3)
linear_r2 <- round(summary(lm(fit$dist~fit$dhat))$adj.r.squared, 3)
## How do I get the newline character to be honored?
nonmetric_label = paste0("Non-metric~fit~italic(R)^2 ==", nonmetric_r2, "~\n Linear~fit~italic(R)^2 ==", linear_r2)
ggplot(tib,
aes(x = diss, y = dist)) +
geom_point(color = "blue") +
geom_line(aes(x = diss, y = dhat), color = "red") +
annotate(
geom = "text",
x = coord_x,
y = coord_y,
hjust = 0,
#vjust = 1,
label = nonmetric_label, parse = TRUE) +
labs(x = "Observed Dissimilarity",
y = "Ordination Distance")
Run Code Online (Sandbox Code Playgroud)
上面的单个注释行应该位于两个单独的行上,如下所示(来自stressplot(fit))。
违规行是
nonmetric_label = paste0("Non-metric~fit~italic(R)^2 ==", nonmetric_r2, "~\n Linear~fit~italic(R)^2 ==", linear_r2)
Run Code Online (Sandbox Code Playgroud)
如果我在 之前不包含波形符\n,那么换行符之后的所有内容都会消失。我尝试了波浪号放置和放置'\n~Linear~fit'额外的单引号和反引号的各种组合。
如何使所需的注释显示在两行上?
一种方法是使用字符串向量作为标签和坐标向量来匹配所需的注释:
nonmetric_label = c(paste0("Non-metric~fit~italic(R)^2 ==", nonmetric_r2),
paste0("Linear~fit~italic(R)^2 ==", linear_r2))
ggplot(tib,
aes(x = diss, y = dist)) +
geom_point(color = "blue") +
geom_step(aes(x = diss, y = dhat), color = "red", direction = "vh") +
annotate(
geom = "text",
x = coord_x,
y = c(coord_y, 0.95*coord_y),
hjust = 0,
#vjust = 1,
label = nonmetric_label, parse = TRUE) +
labs(x = "Observed Dissimilarity",
y = "Ordination Distance")
Run Code Online (Sandbox Code Playgroud)
根据 Jari Oksanen 的建议,我已更改geom_line为geom_step. 为了匹配输出,需要stressplot(fit)一个附加参数。direction = "vh"
| 归档时间: |
|
| 查看次数: |
5335 次 |
| 最近记录: |