【问题标题】:Specify decimal places in r plot text?在 r 绘图文本中指定小数位?
【发布时间】:2014-03-31 17:03:49
【问题描述】:

我尝试格式化在基本图形系统中创建的回归曲线的标签。基本上,这个标签从变量中提取斜率、截距和 r 平方值。一个例子如下:

plot(rnorm(10), type = "n", xlim = c(0, 100), ylim = c(0, 100))
text(x = 0, y = 100, adj = c(0, NA), bquote(paste(y == .(a) * x + .(b), ", R"^2 == .(r2))), cex = 0.7)

但是,这会生成一个看起来不太聪明的标签:

y = 1.159019x+-1.537708, R<sup>2</sup>=0.7924927

我想要的是将数字四舍五入到小数点后第二位,即,

y = 1.16x-1.54, R<sup>2</sup>=0.79

我在text()bquote() 的帮助文档中查找了它,但没有找到太多有用的信息。

我也尝试使用参数nsmall = 2.(a).(b).(r2) 包装在format() 中,但没有成功。

有人可以帮我解决这个问题吗?非常感谢!

ps。我认为我的问题中有一个隐藏的任务。在上面的例子中,b 是负数。我知道我可能会在我的表达式中省略 "+" 运算符,只使用 b 的负号来加入我的等式。但是,如果我事先不知道b 的符号怎么办?有没有一种巧妙的方法来形成标签而不用if()检查这个,然后写两个非常不同的text()版本?再次感谢!

【问题讨论】:

    标签: r plot label decimalformat


    【解决方案1】:

    要指定位数,请使用round(a, digits=2)。但是,您也可以使用 sprintf 来处理等式中的位数和 + 或 -:e.q. %+3.2f,其中% 强制在等式中使用 + 或 - 号,3.2f 控制位数,因此这解决了您的两个问题。我在sprintfhere 中找到了上标问题的解决方案:“B2 是 UTF-8 字符 = ^2 的十六进制代码,\U 是调用该字符的控制序列。”

    # data and regression
    set.seed(1)
    y = 1:10+rnorm(10)
    x = 1:10
    fit = lm(y~x)
    b = coef(fit)[1]
    a = coef(fit)[2]
    r2 = summary(fit)$r.squared
    
    # plot data and regression
    plot(x, y)
    abline(fit, col=2)
    
    # add text to plot with legend() for convenient placement
    legend('topleft', title='option 1', legend=sprintf("y = %3.2fx %+3.2f, R\UB2 = %3.2f", a, b, r2), bty='n', cex=0.7)
    
    # if you prefer a pretty space between plus/minus and b:
    if( b<0) {my_sign = ' - '; b = -b} else { my_sign= ' + '}
    legend('bottomright', title='option 2', legend=sprintf("y = %3.2f x %s %3.2f, R\UB2 = %3.2f", a, my_sign, b, r2), bty='n', cex=0.7)
    

    【讨论】:

    • 非常感谢您的全面回答(使用 round()legend() 的解决方案和建议 - 太棒了!)。还要感谢您包含原始的上标解决方案 - 我很惊讶我的问题对那个问题是如此重复 - 哎呀! ;-P 我喜欢在sprintf() 中使用%+ 来处理标志。最初我有稍微复杂的要求(xy 都有文本下标,例如“[NO2]subscript-urban”),这就是为什么我使用笨拙的bquote() 和嵌套的paste() 进行格式化。猜猜if()这样的标志是不可避免的吗?
    猜你喜欢
    • 1970-01-01
    • 2022-11-19
    • 2017-09-11
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    相关资源
    最近更新 更多