ggplot2中的注释不支持换行符是粘贴和解析的命令 [英] Annotate in ggplot2 does not honor newline is a pasted and parsed command
问题描述
如何获取ggplot2
的annotate
中的paste
和parse
来接受换行符(\ n)?
How do I get paste
and parse
in annotate
of ggplot2
to honor a newline (\n) character?
我正在尝试使用vegan.
软件包中的metaMDS
在ggplot2
中重现NMDS分析的应力图,这是我的MWE,然后是结果图.
I am trying to reproduce in ggplot2
a stressplot of an NMDS analysis using metaMDS
in package vegan.
Here is my MWE, followed by the resulting graph.
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")
上面的单条注释行应位于两条单独的行上,如下所示(来自stressplot(fit)
).
The single annotated line above should be on two separate lines, as shown below (from stressplot(fit)
).
违规行是
nonmetric_label = paste0("Non-metric~fit~italic(R)^2 ==", nonmetric_r2, "~\n Linear~fit~italic(R)^2 ==", linear_r2)
如果我没有在\n
之前加上波浪号,那么换行符之后的所有内容都会消失.我尝试了代字号放置和'\n~Linear~fit'
在其他单引号和反引号中的各种组合.
If I do not include the tilde before \n
, then everything after the newline character disappears. I have tried various combinations of tilde placement and placing '\n~Linear~fit'
in additional single quotes and back-ticks.
如何使所需的注释显示在两行上?
推荐答案
一种方法是将字符串向量用作标签,将坐标向量用于所需的标注:
One approach would be to use a vector of strings as a label and a vector of coordinates which will mach the desired annotation:
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")
根据贾里·奥克萨南(Jari Oksanen)的建议,我已将geom_line
更改为geom_step
.为了匹配stressplot(fit)
的输出,需要一个附加的参数direction = "vh"
.
As per suggestion of Jari Oksanen I have changed geom_line
to geom_step
. To match the output of stressplot(fit)
an additional argument direction = "vh"
is needed.
这篇关于ggplot2中的注释不支持换行符是粘贴和解析的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!