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

ggplot2绘制RDA双图时plot重绘随机出现美学映射错误

ggplot2绘制RDA双图时的随机美学报错问题
  • 用ggplot2为12组冗余分析(RDA)结果绘制双图时出现异常:首次运行plot1代码后调用plot1能正常显示图形,但运行其他绘图代码(如plot3、plot4,无固定规律)后,再次调用plot1会随机抛出如下错误:

Error in check_aesthetics():
! Aesthetics must be either length 1 or the same as the data (8): label
Run rlang::last_error() to see where the error occurred.

  • 有时plot1又能正常显示,报错无固定触发规律。

单图绘制代码如下:

plot1 <- ggplot() +
  geom_point(data = sp, aes(RDA1, RDA2), shape = 21, size = 4, fill = "tomato2") +
  scale_fill_brewer(palette = 'Set2') +
  geom_text_repel(data = sp, aes(RDA1, RDA2, label = sp2$Group), color = "tomato1", size = 4.5) +
  geom_point(data = yz, aes(RDA1, RDA2), size = 3, shape = 24, fill = "dodgerblue3") +
  scale_shape_manual(values = c(22:23)) +
  geom_text_repel(data = yz, aes(RDA1, RDA2, label = yz2$label), color = "dodgerblue2", size = 4.5) +
  labs(x = paste("RDA 1 (", format(100 * ii$cont[[1]][2,1], digits = 3), "%)", sep = ""),
       y = paste("RDA 2 (", format(100 * ii$cont[[1]][2,2], digits = 3), "%)", sep = "")) +
  geom_hline(yintercept = 0, linetype = 3, size = 1, color = "gray50") + 
  geom_vline(xintercept = 0, linetype = 3, size = 1, color = "gray50") +
  guides(shape = guide_legend(title = NULL, color = "black"),
         fill = guide_legend(title = NULL)) +
  theme_bw() + theme(panel.grid = element_blank()) +
  theme(legend.position = "none") +
  theme(legend.text = element_text(colour = "black", size = 13)) +
  theme(axis.title.x = element_text(colour = "black", size = 14),
        axis.text.x = element_text(colour = "black", size = 14)) +
  theme(axis.title.y = element_text(colour = "black", size = 14),
        axis.text.y = element_text(colour = "black", size = 14)) 
plot1

问题根源

报错核心是美学映射的label长度与当前图层数据行数不匹配。你在geom_text_repel中直接引用了外部数据框的列(sp2$Group、yz2$label),而非当前图层绑定的数据框(sp、yz)的列。当其他绘图代码修改了sp2或yz2的行数(比如数据筛选、转换操作改变了数据框长度),就会导致label的长度和sp/yz的行数不一致,触发随机报错。

解决方案

  1. 合并关联数据框:将标签列合并到对应绘图数据框中,确保行数严格匹配:
    # 把sp2的Group列合并到sp数据框
    sp <- cbind(sp, Group = sp2$Group)
    # 把yz2的label列合并到yz数据框
    yz <- cbind(yz, label = yz2$label)
    
  2. 修正美学映射:在geom_text_repel中直接使用合并后的数据框列,不再引用外部数据框:
    geom_text_repel(data = sp, aes(RDA1, RDA2, label = Group), color = "tomato1", size = 4.5) +
    # ...
    geom_text_repel(data = yz, aes(RDA1, RDA2, label = label), color = "dodgerblue2", size = 4.5) +
    
  3. 隔离绘图数据:绘制不同RDA图时,使用独立的变量名(比如sp_plot1、sp_plot3分别对应不同图的物种数据),避免后续绘图代码修改之前绘图依赖的数据框,防止全局数据污染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:36:30