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

如何在Base R绘图系统中绘制点范围图与带状图?

在Base R中复现点范围图与带状图

1. 点范围图(对应ggplot2的geom_pointrange)

无需额外包,仅用Base R就能实现,核心通过segments绘制置信区间线段、points绘制系数点:

# 拟合模型
mod <- lm(mpg ~ hp + factor(cyl), mtcars)
# 提取系数与置信区间
coef_dat <- data.frame(
  x = factor(names(coef(mod))),
  y = coef(mod),
  ymin = confint(mod)[, 1],
  ymax = confint(mod)[, 2]
)

# 初始化绘图画布
plot(
  x = as.numeric(coef_dat$x), 
  y = coef_dat$y,
  xlim = c(0.5, length(coef_dat$x) + 0.5),
  ylim = range(c(coef_dat$ymin, coef_dat$ymax)),
  type = "n",
  xaxt = "n"
)
# 绘制置信区间垂直线段
segments(
  x0 = as.numeric(coef_dat$x),
  y0 = coef_dat$ymin,
  x1 = as.numeric(coef_dat$x),
  y1 = coef_dat$ymax
)
# 绘制系数点
points(
  x = as.numeric(coef_dat$x),
  y = coef_dat$y,
  pch = 16
)
# 添加x轴变量名标签
axis(1, at = as.numeric(coef_dat$x), labels = levels(coef_dat$x))

2. 带状图(对应ggplot2的geom_ribbon)

用predict获取预测区间,polygon绘制置信带,lines绘制拟合线:

# 拟合模型
mod <- lm(mpg ~ hp, mtcars)
# 生成hp的连续序列用于预测
new_hp <- seq(min(mtcars$hp), max(mtcars$hp), length.out = 100)
# 获取预测值与置信区间
pred_dat <- predict(mod, newdata = data.frame(hp = new_hp), interval = "confidence")
pred_dat <- data.frame(
  hp = new_hp, 
  estimate = pred_dat[, "fit"], 
  conf.low = pred_dat[, "lwr"], 
  conf.high = pred_dat[, "upr"]
)

# 初始化绘图画布
plot(
  x = pred_dat$hp,
  y = pred_dat$estimate,
  ylim = range(c(pred_dat$conf.low, pred_dat$conf.high)),
  type = "n"
)
# 绘制半透明置信带
polygon(
  x = c(pred_dat$hp, rev(pred_dat$hp)),
  y = c(pred_dat$conf.low, rev(pred_dat$conf.high)),
  col = adjustcolor("black", alpha.f = 0.3),
  border = NA
)
# 绘制拟合线
lines(pred_dat$hp, pred_dat$estimate)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:02:24