ggplot中的多个最小二乘二次拟合

时间:2019-03-08 22:49:48

标签: r ggplot2 quadratic-curve

  

请注意,根据问题4构造的图形显示为二次方   或 log_wages exp 之间的弯曲关系。下一个   任务是为每个种族级别“黑色”绘制三个二次函数,   “白色”和“其他”。要估算二次拟合,您可以使用   以下函数 quad_fit

```{r}
quad_fit <- function(data_sub) {
  return(lm(log_wage~exp+I(exp^2),data=data_sub)$coefficients)
}
quad_fit(salary_data)
```
  

上面的函数计算最小二乘二次拟合和   返回系数a1,a2,a3,其中

     

Y(hat)= a1 + a2x + a3x ^ 2

     

其中Y(hat)= log(wage),x = exp

     

使用 ggplot 完成此任务或将基本R图形用于   部分分数。确保包含图例和适当的标签。

我的尝试

blackfit <- quad_fit(salary_data[salary_data$race == "black",])
whitefit <- quad_fit(salary_data[salary_data$race == "white",])
otherfit <- quad_fit(salary_data[salary_data$race == "other",])

yblack <- blackfit[1] + blackfit[2]*salary_data$exp + blackfit[3]*(salary_data$exp)^2
ywhite <- whitefit[1] + whitefit[2]*salary_data$exp + whitefit[3]*(salary_data$exp)^2
yother <- otherfit[1] + otherfit[2]*salary_data$exp + otherfit[3]*(salary_data$exp)^2

soloblack <- salary_data[salary_data$race == "black",]
solowhite <- salary_data[salary_data$race == "white",]
soloother <- salary_data[salary_data$race == "other",]

ggplot(data = soloblack) +
  geom_point(aes(x = exp, y = log_wage)) +
  stat_smooth(aes(y = log_wage, x = exp), formula = y ~ yblack)

这仅是第一次尝试使用race ==“ black”过滤的数据。 我不清楚该公式的外观,因为通过quad_fit函数,它似乎已经为您进行了计算。

1 个答案:

答案 0 :(得分:1)

考虑使用quad_fit的输出来绘制拟合值(如@StefanK here所示),并使用by绘制 race 的所有不同值:

reg_plot <- function(sub) {
   # PREDICTED DATA FOR LINE PLOT
   q_fit <- quad_fit(sub)
   predicted_df <- data.frame(wage_pred = predict(q_fit, sub), exp = sub$exp)

   # ORIGINAL SCATTER PLOT WITH PREDICTED LINE
   ggplot(data = sub) + 
     geom_point(aes(x = exp, y = log_wage, alpha = exp)) +
     labs(x = "Job Experience", y = "Log of Wage", 
          title = paste("Wage and Job Experience Plot for",    
                        sub$race[[1]], "in Salary Dataset") 
     geom_line(color='red', data = predicted_df, aes(x = exp, y = wage_pred))
}

# RUN GRAPHS FOR EACH RACE
by(salary_data, salary_data$race, reg_plot)