fork download
  1. # your code goes here
  2. # 加载绘图包
  3. library(ggplot2)
  4.  
  5. # 原始数据
  6. population <- c(54167, 55196, 56300, 57482, 58796, 60266, 61465, 62828,
  7. 64653, 65994, 67207, 66207, 65859, 67295, 69172, 70499,
  8. 72538, 74542, 76368, 78534, 80671, 82992, 85229, 87177,
  9. 89211, 90859, 92420, 93717, 94974, 96259, 97542, 98705,
  10. 100072, 101654, 103008, 104357, 105851, 107507, 109300, 111026,
  11. 112704, 114333, 115823, 117171, 118517, 119850, 121121, 122389,
  12. 123626, 124761, 125786, 126743, 127627, 128453, 129227, 129988,
  13. 130756, 131448, 132129, 132802)
  14. years <- 1949:2008
  15. df <- data.frame(year = years, population = population)
  16.  
  17. # 线性模型
  18. linear_model <- lm(population ~ year, data = df)
  19. df$linear_fit <- predict(linear_model)
  20.  
  21. # 二次多项式模型
  22. poly_model <- lm(population ~ poly(year, 2), data = df)
  23. df$poly_fit <- predict(poly_model)
  24.  
  25. # 指数模型
  26. df$log_population <- log(df$population)
  27. exp_model <- lm(log_population ~ year, data = df)
  28. df$exp_fit <- exp(predict(exp_model))
  29.  
  30. # 绘图
  31. ggplot(df, aes(x = year)) +
  32. geom_point(aes(y = population), label = "原始数据") +
  33. geom_line(aes(y = linear_fit, color = "线性模型")) +
  34. geom_line(aes(y = poly_fit, color = "二次多项式模型")) +
  35. geom_line(aes(y = exp_fit, color = "指数模型")) +
  36. labs(x = "年份", y = "人口总数(万人)", title = "不同模型对1949 - 2008年人口数据的拟合") +
  37. scale_color_manual(values = c("blue", "red", "green"))
  38.  
Success #stdin #stdout #stderr 1.26s 64168KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Warning: Ignoring unknown parameters: label
There were 50 or more warnings (use warnings() to see the first 50)