Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否在r绘图文本中指定小数点?_R_Plot_Label_Decimalformat - Fatal编程技术网

是否在r绘图文本中指定小数点?

是否在r绘图文本中指定小数点?,r,plot,label,decimalformat,R,Plot,Label,Decimalformat,我试图格式化在基本图形系统中创建的回归曲线的标签。基本上,这个标签从变量中提取斜率、截距和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 =

我试图格式化在基本图形系统中创建的回归曲线的标签。基本上,这个标签从变量中提取斜率、截距和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.159019x+-1.537708,R2=0.7924927
我想把数字四舍五入到小数点后第二位,即

y = 1.16x-1.54, R<sup>2</sup>=0.79
y=1.16x-1.54,R2=0.79
我在两个帮助文档中都查找了
text()
bquote()
,但没有找到多少有用的信息

我还尝试用参数
nsmall=2
(a)
(b)
(r2)
包装成
格式()

有人能帮我吗?非常感谢


我想在我的问题中有一个隐藏的探索。在上面的示例中,
b
为负值。我知道我可以在表达式中省略
“+”
操作符,只使用
b的负号来连接我的等式。但是,如果我事先不知道
b
的符号怎么办?有没有一种巧妙的方法可以在不使用
if()
检查标签的情况下形成标签,然后编写两个稍有不同的
text()
?再次感谢

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

#数据与回归
种子(1)
y=1:10+rnorm(10)
x=1:10
拟合=lm(y~x)
b=系数(拟合)[1]
a=系数(拟合)[2]
r2=汇总(拟合)$r.平方
#绘图数据和回归
绘图(x,y)
abline(配合,柱=2)
#使用图例()将文本添加到绘图中以方便放置
图例('topleft',title='option 1',图例=sprintf(“y=%3.2fx%+3.2f,R\UB2=%3.2f”,a、b、r2),bty='n',cex=0.7)
#如果你喜欢在正负和b之间有一个相当大的空间:

如果(b非常感谢您的全面回答(使用
round()
legend()
的解决方案和建议-这些都很好!)。也感谢您包含了原始的上标解决方案-我很惊讶我的问题对这一个的重复性-哎呀!;-P我喜欢在
sprintf()中使用
%+
用于处理标志。最初,我有稍微复杂的要求(x
和y
都有文本下标,例如“[NO2]下标urban”),这就是为什么我使用笨拙的
bquote()
和嵌套的
粘贴()
进行格式设置的原因。猜测
if()
对于标志来说是不可避免的吗?
# 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)