You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中为中国GDP数据创建线性回归线并绘图?

在R中处理中国人均GDP的线性回归与可视化

1. 数据获取与预处理

可以用wbstats包直接从世界银行获取目标数据,无需手动下载:

# 安装并加载所需包
install.packages("wbstats")
install.packages("ggplot2")
library(wbstats)
library(ggplot2)

# 获取中国人均GDP(不变价美元)数据,指标代码NY.GDP.PCAP.KD
china_gdp <- wb_data(indicator = "NY.GDP.PCAP.KD", 
                     country = "CHN", 
                     start_date = 1960, 
                     end_date = 2023)

# 整理数据,保留年份和GDP列并重命名
china_gdp_clean <- china_gdp[, c("date", "NY.GDP.PCAP.KD")]
colnames(china_gdp_clean) <- c("year", "gdp_per_capita")

2. 构建线性回归模型

按照你构思的y=B₀+B₁x形式,这里y代表人均GDP,x代表年份:

# 拟合线性回归模型
gdp_model <- lm(gdp_per_capita ~ year, data = china_gdp_clean)

# 查看模型结果,包含系数、拟合度、显著性等信息
summary(gdp_model)

3. 绘制回归可视化图形

用ggplot2绘制散点图+回归线,横轴为年份,纵轴为人均GDP:

ggplot(china_gdp_clean, aes(x = year, y = gdp_per_capita)) +
  geom_point(color = "#2ecc71", alpha = 0.7) +  # 绘制原始数据散点
  geom_smooth(method = "lm", color = "#e74c3c", linewidth = 1) +  # 添加线性回归线
  labs(x = "年份", y = "人均GDP(不变价美元)", title = "中国人均GDP随年份变化的线性回归") +
  theme_minimal()

验证示例代码正确性

你构思的示例代码可以直接运行验证:

x <- c(0,1,2,3,4)
y <- c(0,1,2,3,4)
test_model <- lm(y ~ x)
summary(test_model)
# 输出结果会显示截距B₀=0,系数B₁=1,完全符合预期的线性关系

内容的提问来源于stack exchange,提问作者Cassie Tran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:58:07