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

ggplot2中能否为shape美学映射多变量?NMDS绘图求助

解决思路:用复合因子映射shape美学

你没法直接把一个shape美学同时映射两个变量,但可以把HCC和Depth组合成复合因子,用这个复合因子来映射shape,这样就能实现「不同HCC对应基础形状,不同Depth控制填充/空心」的效果。

具体操作步骤如下:

1. 创建复合因子列

先在你的数据框site.scrs里生成一个新列,把HCC(转成因子)和Depth组合起来,每个组合对应一个唯一的水平:

site.scrs$hcc_depth <- interaction(factor(site.scrs$HCC), site.scrs$Depth, sep = "_")

或者用paste也能实现:

site.scrs$hcc_depth <- factor(paste(site.scrs$HCC, site.scrs$Depth, sep = "_"))

2. 修改ggplot代码,映射复合因子到shape

把原来的shape = factor(site.scrs$HCC)替换成shape = hcc_depth,然后用scale_shape_manual()手动指定每个复合水平对应的形状:

nmds.holistic <- ggplot(site.scrs, aes(x=NMDS1, y=NMDS2))+ 
  geom_point(
    aes(
      size = factor(Rugosity), 
      colour = MA, 
      shape = hcc_depth  # 映射复合因子到shape
    )
  )+ 
  coord_fixed() +
  theme_classic() + 
  theme(
    panel.background = element_rect(
      fill = NA, 
      colour = "black", 
      linewidth = 1, 
      linetype = "solid")
  ) +
  labs(size = "Rugosity", shape = "HCC + Depth")+  # 调整shape的图例标题
  scale_shape_manual(
    values = c(
      # 假设HCC有A、B两个类别,Depth有浅、深两个取值
      "A_浅" = 16, "A_深" = 21,  # A类:浅深度用实心圆,深深度用空心圆
      "B_浅" = 17, "B_深" = 22   # B类:浅深度用实心三角,深深度用空心三角
    )
  ) +
  theme(
    legend.position = "right", 
    legend.text = element_text(size = 12), 
    legend.title = element_text(size = 12), 
    axis.text = element_text(size = 10)
  )

nmds.holistic + labs(title = "Holistic")

3. 优化图例(可选)

如果觉得复合因子的图例标签太啰嗦,可以用labels参数修改:

scale_shape_manual(
  values = c("A_浅" = 16, "A_深" = 21, "B_浅" = 17, "B_深" = 22),
  labels = c("A (浅)", "A (深)", "B (浅)", "B (深)")
)

或者用guide_legend()把图例按HCC分组,让结构更清晰:

scale_shape_manual(
  values = c("A_浅" = 16, "A_深" = 21, "B_浅" = 17, "B_深" = 22),
  labels = c("浅", "深", "浅", "深")
) +
guides(
  shape = guide_legend(
    title = "HCC + Depth",
    ncol = 2,
    override.aes = list(size = 5),  # 放大图例里的点,方便看形状
    keywidth = unit(2, "cm")
  )
)

关键说明

  • 填充/空心形状对应:ggplot里的形状编号,1-14是空心,15-20是实心,21-25是可自定义填充色的空心(你这里用colour映射MA,21-25的边框会是MA的颜色,填充默认白色,完全满足「是否填充」的需求)。
  • 复合因子的水平要和你实际数据里的HCC、Depth取值对应,比如如果HCC取值是1、2、3,Depth是"shallow"、"deep",那复合水平就是"1_shallow"、"1_deep"等,要在values里一一匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:37:06