在 R 中,除了 pretty10exp() 之外,我还使用 paste() 而不是 c() 时,为什么图例中会出现笨拙的输出?

In R, why is there awkward output in the legend when I am using paste() instead of c() in addition to pretty10exp()?

我试图让这个情节的图例变得漂亮,所以我需要有一个实际的上标,这就是我使用 sfsmisc 库中的 pretty10exp() 函数的原因。它在我使用 c() 函数时有效。

不过,我也在努力让字符串和科学记数法数字保持在同一行。 legend() 被分成两行,我认为这是由于 c()。我以为我可以使用 paste(),但由于某些原因现在输出不正确。

plot(1:12)
pVal <- 4
legend("topright", legend = c("P value:", sfsmisc::pretty10exp(pVal)), cex = 1.5)

legend("topright", legend = paste("P value:", sfsmisc::pretty10exp(pVal)), cex = 1.5)

pVal 是以科学记数法表示的任意数字。第二行产生如下输出:"P value: (significand) %*% 10^-4"。第一行也没有给我我想要的。我该如何解决这个问题?

pretty10exp returns 一个表达式,它允许它使用 ?plotmath 功能来制作漂亮的数字。使用表达式时,您不能只将值粘贴到类似字符串中。您需要使用一组特殊的函数来操作它们。其中一个函数是 substitute。你可以做到

plot(1:12)
pVal <- 4
legend("topright", cex = 1.5, 
    legend = substitute("P value: "*x, list(x=sfsmisc::pretty10exp(pVal)[[1]])) )

我们使用substitute()pretty10exp中获取表达式中包含的值,并在其前面加上您想要的标签。 (我们使用 * 来连接而不是 paste() 因为 plotmath 允许它)

这就是我要做的:

fun <- function(text, pVal) {
  y <- floor(log10(pVal))
  x <- pVal / 10^y
  bquote(.(text)*":" ~ .(x) %.% 10 ^ .(y))
}

plot.new()
text(0.5,0.7,fun("P value", 0.4))
text(0.5, 0.3, fun("P value", signif(1/pi, 1)))

不需要包。