首页 > 解决方案 > 当我的 aes 函数中未提及 XXX 时,geom_text 返回“找不到对象 XXX”错误

问题描述

当我运行下面的代码时,我得到了错误Error in FUN(X[[i]], ...) : object 'typoft' not found。我有两个 geom_texts,因为我在情节顶部放置了更多文本。谁能在这里帮助我,让我知道为什么会有

标签: rggplot2

解决方案


您的问题来自这样一个事实,即当您aes在调用中定义 an 时,如果未覆盖ggplot()这些设置,则这些设置将被其后的所有设置继承。geom_*

如果我们将您的问题简化为最小形式,我们可以清楚地看到这一点。我们可以geom_text仅用最后一个复制您的问题:

ggplot(gb, aes(x = y, y = y1, fill = typeoft)) + 
    geom_text(data = labdat, aes(x = x,y = y,label = label))

Error in FUN(X[[i]], ...) : object 'typeoft' not found

发生这种情况是因为当您定义aesin时,您为、和ggplot设置了一个值。当您调用时,和的值会被覆盖,但 fill 的值不会。所以for实际上看起来像这样:但是由于您没有在 object中命名的变量,因此它会返回错误。xyfillaesgeom_textxyaesgeom_text aes(x = x, y = y, label = label, fill = typeoft)typeoftlabdat

geom_text我们可以通过给你的论点来阻止这种行为inherit.aes = FALSE

# This works!
ggplot(gb, aes(x = y, y = y1, fill = typeoft)) + 
    geom_text(data = labdat,aes(x = x, y = y, label = label), inherit.aes = FALSE)

现在,aesforgeom_text将只包含您告诉它拥有的内容。


推荐阅读