如何将 RMSE、斜率、截距、r^2 添加到 R 图中? [英] How to add RMSE, slope, intercept, r^2 to R plot?

查看:26
本文介绍了如何将 RMSE、斜率、截距、r^2 添加到 R 图中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 R 将 RMSE、斜率、截距和 r^2 添加到绘图中?我附上了一个带有示例数据的脚本,它与我的真实数据集格式相似——不幸的是,我处于停滞状态.是否有比从方程创建对象并将其插入 text() 更简单的方法将这些统计信息添加到图形中?理想情况下,我希望将统计信息堆叠在图表上.我怎样才能做到这一点?

How can I add RMSE, slope, intercept and r^2 to a plot using R? I have attached a script with sample data, which is a similar format to my real dataset--unfortunately, I am at a stand-still. Is there an easier way to add these statistics to the graph than to create an object from an equation and insert that into text()? I would ideally like the statistics to be displayed stacked on the graph. How can I accomplish this?

## Generate Sample Data
x = c(2,4,6,8,9,4,5,7,8,9,10)
y = c(4,7,6,5,8,9,5,6,7,9,10)

# Create a dataframe to resemble existing data
mydata = data.frame(x,y)

#Plot the data
plot(mydata$x,mydata$y)
abline(fit <- lm(y~x))

# Calculate RMSE
model = sqrt(deviance(fit)/df.residual(fit))

# Add RMSE value to plot
text(3,9,model)

推荐答案

这是一个使用基本图形和 ?plotmath 绘制绘图并对其进行注释的版本

Here is a version using base graphics and ?plotmath to draw the plot and annotate it

## Generate Sample Data
x = c(2,4,6,8,9,4,5,7,8,9,10)
y = c(4,7,6,5,8,9,5,6,7,9,10)

## Create a dataframe to resemble existing data
mydata = data.frame(x,y)

## fit model
fit <- lm(y~x, data = mydata)

接下来计算要在注释中显示的值.为此,我更喜欢 bquote(),其中 .(foo) 中标记的任何内容都将替换为对象 foo 的值.@mnel 在评论中指出的答案使用 substitute() 来实现相同的目的,但通过不同的方式.因此,我在工作区中为您可能希望在注释中显示的每个值创建对象:

Next calculate the values you want to appear in the annotation. I prefer bquote() for this, where anything marked-up in .(foo) will be replaced by the value of the object foo. The Answer @mnel points you to in the comments uses substitute() to achieve the same thing but via different means. So I create objects in the workspace for each value you might wish to display in the annotation:

## Calculate RMSE and other values
rmse <- round(sqrt(mean(resid(fit)^2)), 2)
coefs <- coef(fit)
b0 <- round(coefs[1], 2)
b1 <- round(coefs[2],2)
r2 <- round(summary(fit)$r.squared, 2)

现在使用 ?plotmath 中描述的结构构建方程:

Now build up the equation using constructs described in ?plotmath:

eqn <- bquote(italic(y) == .(b0) + .(b1)*italic(x) * "," ~~ 
                  r^2 == .(r2) * "," ~~ RMSE == .(rmse))

完成后,您可以绘制绘图并用您的表达式对其进行注释

Once that is done you can draw the plot and annotate it with your expression

## Plot the data
plot(y ~ x, data = mydata)
abline(fit)
text(2, 10, eqn, pos = 4)

给出:

这篇关于如何将 RMSE、斜率、截距、r^2 添加到 R 图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆