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

ggplot2分组散点图绘制失败:如何按两组实现变量散点图?

解决ggplot2分组绘制散点图+拟合曲线的问题

我来帮你搞定这个可视化需求!你想要按Religion和Macro.Region两个维度,绘制Killed与Terr..Attacks的散点图及拟合曲线,下面是几种实用的实现方案,你可以根据自己的展示需求选择:

1. 双变量分面(最清晰的分组展示)

这种方式会把每个Religion和Macro.Region的组合单独做成子图,视觉上最直观,适合对比不同分组的关系:

# 先加载ggplot2包
library(ggplot2)

ggplot(terr, aes(x = Terr..Attacks, y = Killed)) +
  # 散点:用Religion区分颜色,增加透明度避免重叠
  geom_point(aes(color = Religion), alpha = 0.7) +
  # 线性拟合曲线:按Religion分组绘制,不显示置信区间
  geom_smooth(method = "lm", se = FALSE, aes(color = Religion)) +
  # 按Religion(行)和Macro.Region(列)分面
  facet_grid(Religion ~ Macro.Region) +
  # 自定义标签让图表更易读
  labs(
    title = "Killed vs Terrorist Attacks by Religion & Macro Region",
    x = "Number of Terrorist Attacks",
    y = "Number of People Killed",
    color = "Religion"
  ) +
  # 用简洁的主题
  theme_minimal()

2. 同一画布内双变量区分(适合紧凑展示)

如果不想拆分多个子图,可以在同一个图里用颜色区分Religion、形状区分Macro.Region,同时拟合曲线也对应分组:

ggplot(terr, aes(x = Terr..Attacks, y = Killed)) +
  geom_point(
    aes(color = Religion, shape = Macro.Region),
    size = 3, alpha = 0.7
  ) +
  geom_smooth(
    method = "lm", se = FALSE,
    aes(color = Religion, linetype = Macro.Region)
  ) +
  labs(
    title = "Killed vs Terrorist Attacks (Dual Group Breakdown)",
    x = "Number of Terrorist Attacks",
    y = "Number of People Killed",
    color = "Religion",
    shape = "Macro Region",
    linetype = "Macro Region"
  ) +
  theme_minimal()

3. 单变量分面+另一变量嵌套(侧重区域对比)

如果更关注Macro.Region的差异,每个区域内再对比Religion的情况,可以用这种方式:

ggplot(terr, aes(x = Terr..Attacks, y = Killed)) +
  geom_point(aes(color = Religion), alpha = 0.7) +
  geom_smooth(method = "lm", se = FALSE, aes(color = Religion)) +
  # 按Macro.Region分面,自动排列子图
  facet_wrap(~ Macro.Region) +
  labs(
    title = "Killed vs Terrorist Attacks by Macro Region (Religion Breakdown)",
    x = "Number of Terrorist Attacks",
    y = "Number of People Killed",
    color = "Religion"
  ) +
  theme_minimal()

小提示:解决可能的问题

  • 你之前没得到预期结果,大概率是没有在aes()里正确指定分组映射(比如用color/group来关联要分组的变量),或者分面逻辑不对。
  • 你的数据集里有重复行,如果想避免重复点,可以用dplyr::distinct(terr)去重后再绘图:
    library(dplyr)
    terr_unique <- distinct(terr)
    
  • 如果需要非线性拟合,把geom_smooth()里的method改成"loess"或者其他你需要的方法即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:51:00