簡體   English   中英

ggplot中的多個最小二乘二次擬合

[英]Multiple least squares quadratic fit in ggplot

請注意,根據問題 4 構建的圖形顯示了log_wagesexp之間的二次或曲線關系。 下一個任務是為每個種族級別“黑色”、“白色”和“其他”繪制三個二次函數。 要估計二次擬合,您可以使用以下函數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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM