【问题标题】:Legend in two rows in R using bquote使用 bquote 在 R 中的两行中的图例
【发布时间】:2016-10-21 16:21:18
【问题描述】:

我想使用bquote 绘制图例,但在图例中添加两行时遇到问题。例如:

这行得通:

plot(1:10)
r2=0.99
legend("topleft",legend=bquote(R^{2} ~ "="  ~.(r2)),bty = "n")

但如果我添加第二行:

plot(1:10)
r2=0.99
pval=0.01
legend("topleft",legend=c(bquote(R^{2} ~ "="  ~.(r2)),paste("P-value =",pval)),bty = "n")

图例中我的向量的整个第一个元素是“扩展的”。这是为什么呢?

【问题讨论】:

    标签: r plot legend


    【解决方案1】:

    这是因为c-function 无法连接bquote 返回的对象类型的多个实例。大多数人认为 bquote 返回 R 表达式,但事实并非如此。它返回调用并且它们不会连接到列表中。您需要将expression 函数应用于多次调用bquote 返回的项目,以将它们放入“表达式”列表中。 2005 年,Thomas Lumley 在 Rhelp 上对此进行了解释:

    legend("topleft",legend=do.call( 'expression', 
                                    list( bquote( R^{2} == .(r2)), 
                                          bquote( "P-value" == .(pval)))  ),
                      bty = "n")
    

    如果您想将此参数构建为图例,还有另一种方法,它允许将表达式与c() 一起串起来。重新定义 bquote 以返回表达式:

    bquote2 <- function (expr, where = parent.frame()) 
    {
        unquote <- function(e) if (is.pairlist(e)) 
            as.pairlist(lapply(e, unquote))
        else if (length(e) <= 1L) 
            e
        else if (e[[1L]] == as.name(".")) 
            eval(e[[2L]], where)
        else as.call(lapply(e, unquote))
        as.expression( unquote(substitute(expr)) )
    }
    legend("topleft",
            legend=c( bquote2(R^{2} ~ "="  ~.(r2)),
                      bquote2(paste("P-value =",pval))), 
            bty = "n")
    

    【讨论】:

    • 啊!我认为它们是语言对象,但我不知道它们可以这样组合。
    • 如果 bquote 确实返回了一个表达式,我相信您将能够使用c,因为表达式列表是类似列表的对象。我看看能不能修改一下它的代码。
    【解决方案2】:

    我设法通过以下方式制作了您想要的东西:

    textleg <- substitute(atop(paste(R^2==k),
                               plain(P-value)==j), list(k = r2, j=pval))
    legend("topleft",legend=textleg,bty = "n")
    

    编辑:

    @42- 建议添加引号会将我在“P 值”中的减号变成连字符:

    【讨论】:

    • 是的,非常接近。我仍然对没有正确对齐的行感到恼火:P
    • (非常小的一点):我同意您使用更多绘图运算符的努力,但 Pvalue 之间的减号比您引用“P -值”。
    猜你喜欢
    • 1970-01-01
    • 2014-03-20
    • 2015-12-29
    • 2018-06-11
    • 2015-10-03
    • 2014-12-13
    • 2015-01-23
    • 2021-03-02
    相关资源
    最近更新 更多