如何在r

时间:2017-12-14 22:14:58

标签: r ggplot2 linear-regression coefficients

您好我已经创建了一个线性模型和一个回归图 - 但是,我想在模型本身上得到模型结果 - 如下图所示:

example plot

如何在情节中显示关键结果?下面是我的情节代码:

library(ggplot2)
ggplot(HP_crime15, aes (x = as.numeric(HP_crime15$Theft15), y = 
as.numeric(HP_crime15$X2015))) + geom_point(shape=1) + 
geom_smooth(method=lm) + xlab ("Recorded number of Thefts") + 
ylab("House prices (£)") + ggtitle("Title") 

2 个答案:

答案 0 :(得分:1)

理想情况下,好的问题是通过提供reproducible example来解决问题的问题。无论如何,我已经分两步解决了这个问题;

步骤1:确定线性回归模型;

fit1 <- lm(Sepal.Length ~ Petal.Width, data = iris)

第2步:绘制模型;

library (ggplot2)
ggplot(fit1$model, aes_string(x = names(fit1$model)[2], y = names(fit1$model)[1])) + 
  geom_point() +
  stat_smooth(method = "lm", col = "red") +
  labs(title = paste("Adj R2 = ",signif(summary(fit1)$adj.r.squared, 5),
                     "Intercept =",signif(fit1$coef[[1]],5 ),
                     " Slope =",signif(fit1$coef[[2]], 5),
                     " P =",signif(summary(fit1)$coef[2,4], 5)))

Plot

答案 1 :(得分:1)

这是另一个选项:您可以在标题中添加标签,而不是将统计信息添加到标题中:

library (ggplot2)

fit1 <- lm(Sepal.Length ~ Petal.Width, data = iris)   
ggplot(fit1$model, aes_string(x = names(fit1$model)[2], y = names(fit1$model)[1])) + 
  geom_point() +
  stat_smooth(method = "lm", col = "red") +
  geom_label(aes(x = 0, y = 7.5), hjust = 0, 
             label = paste("Adj R2 = ",signif(summary(fit1)$adj.r.squared, 5),
                                               "\nIntercept =",signif(fit1$coef[[1]],5 ),
                                               " \nSlope =",signif(fit1$coef[[2]], 5),
                                               " \nP =",signif(summary(fit1)$coef[2,4], 5)))

enter image description here