[英]Multiple least squares quadratic fit in ggplot
请注意,根据问题 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(帽子) = 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)
这只是对使用 for Race == "black" 过滤的数据的第一次尝试。 我不清楚公式应该是什么样子,因为通过 quad_fit 函数它似乎已经为你做了计算。
考虑使用绘图输出拟合值quad_fit
(如图@StefanK这里),并使用by
跨种族的所有不同值的情节:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.