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

如何在R中同图绘制模型训练数据与预测区域?含可视化优化

问题2:用填充区域/多边形替代点绘制预测区域

散点绘制区域不够直观,推荐两种实用方法,适配不同需求:

方法1:用geom_tile绘制填充区域(最简便)

你的df.test是规则网格数据,刚好适合用geom_tile生成连续的填充区域,还可以叠加边界线增强清晰度:

ggplot(df.test, aes(x=x,y=y)) +
  # 绘制半透明的预测填充区域
  geom_tile(aes(fill=z), alpha=0.6) +
  scale_fill_manual(values=col_light, name="预测类别") +
  # 添加类别边界线(可选)
  geom_contour(aes(z=as.numeric(z)), color="black", linewidth=0.5) +
  # 叠加训练数据点
  geom_point(data=df.train, aes(x=x,y=y, color=z), pch=15, size=2) +
  scale_color_manual(values=col_dark, name="训练类别") +
  theme_minimal()

方法2:针对Bootstrap置信区域的优化

对于你用Bootstrap计算的95%一致预测区域(df.test.1),同样可以用geom_tile绘制,突出高置信度的预测范围:

ggplot(df.test.1, aes(x=x,y=y)) +
  geom_tile(aes(fill=z), alpha=0.7) +
  scale_fill_manual(values=col_light, name="一致预测类别") +
  geom_contour(aes(z=as.numeric(z)), color="darkgray", linewidth=0.8) +
  geom_point(data=df.train, aes(x=x,y=y, color=z), pch=15, size=2) +
  scale_color_manual(values=col_dark, name="训练类别") +
  labs(title="LDA 95% Bootstrap一致预测区域") +
  theme_minimal()

进阶:用多边形绘制精确边界

如果需要更精准的类别轮廓,可以借助sf包将网格点转换为凸包多边形:

library(sf)
library(dplyr)

# 将测试网格数据转换为sf点对象
df_sf <- st_as_sf(df.test, coords = c("x", "y"))

# 按预测类别分组,生成凸包多边形
df_polygons <- df_sf %>%
  group_by(z) %>%
  summarize(geometry = st_union(st_convex_hull(st_combine(geometry))))

# 绘图
ggplot() +
  geom_sf(data=df_polygons, aes(fill=z), alpha=0.5) +
  scale_fill_manual(values=col_light) +
  geom_point(data=df.train, aes(x=x,y=y, color=z), pch=15, size=2) +
  scale_color_manual(values=col_dark)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:10:00