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

如何用ggplot2实现基于三变量的点颜色、形状及填充/空心设置

解决方案

要实现三个视觉映射规则,你可以通过以下两种方法处理样本量对应的填充/空心状态:

方法一:创建组合变量映射到形状

直接将「数据采集类型」和「样本量是否超过20」组合成一个新变量,为每种组合指定唯一的形状(实心/空心区分样本量,形状样式区分数据类型):

步骤1:处理数据,生成组合变量

# 结合数据采集类型与样本量分组,生成新变量
phys_MLW$shape_group <- paste(
  phys_MLW$data_collection,
  ifelse(phys_MLW$no_seeds > 20, "large", "small"),
  sep = "_"
)

步骤2:绘制图表并自定义形状

ggplot(phys_MLW, aes(x = year, y = avg_width, color = site)) + 
  # 将组合变量映射到shape
  geom_point(aes(shape = shape_group), size = 2.5) + 
  geom_line() + 
  scale_x_continuous(
    breaks = round(seq(min(phys_MLW$year), max(phys_MLW$year), by = 2))
  ) + 
  labs(
    x = "Year", 
    y = "Average Width", 
    col = "Site",
    shape = "Sample Source & Size"
  ) + 
  # 手动指定每种组合对应的形状与图例标签
  scale_shape_manual(
    values = c(
      "indiv_phys_large" = 19,  # 实心圆:单株采集 + 样本量>20
      "indiv_phys_small" = 1,   # 空心圆:单株采集 + 样本量≤20
      "site_phys_large" = 15,   # 实心正方形:全域调查 + 样本量>20
      "site_phys_small" = 0     # 空心正方形:全域调查 + 样本量≤20
    ),
    labels = c(
      "indiv_phys_large" = "Individual trees (n>20)",
      "indiv_phys_small" = "Individual trees (n≤20)",
      "site_phys_large" = "Sitewide (n>20)",
      "site_phys_small" = "Sitewide (n≤20)"
    )
  )

方法二:分离形状与填充映射

使用支持填充的形状(如21、22),将「数据采集类型」映射到形状样式,「样本量是否超过20」映射到填充状态:

步骤1:生成样本量分组变量

# 标记样本量是否超过20
phys_MLW$size_group <- ifelse(
  phys_MLW$no_seeds > 20, 
  "Large (n>20)", 
  "Small (n≤20)"
)

步骤2:绘制图表并设置填充

ggplot(phys_MLW, aes(x = year, y = avg_width, color = site)) + 
  # 形状映射数据类型,填充映射样本量分组
  geom_point(aes(shape = data_collection, fill = size_group), size = 2.5) + 
  geom_line() + 
  scale_x_continuous(
    breaks = round(seq(min(phys_MLW$year), max(phys_MLW$year), by = 2))
  ) + 
  labs(
    x = "Year", 
    y = "Average Width", 
    col = "Site",
    shape = "Source of samples",
    fill = "Sample Size"
  ) + 
  # 指定数据类型对应的填充式形状
  scale_shape_manual(
    values = c(21, 22),  # 21=带填充的圆,22=带填充的正方形
    labels = c("Individual trees", "Sitewide")
  ) + 
  # 大样本填充颜色,小样本设为空心(NA)
  scale_fill_manual(
    values = c("Large (n>20)" = "black", "Small (n≤20)" = NA)
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:52:42