尝试向带有 geom_text 的点添加文本标签时如何处理 "Error in FUN(X[[i]],..."?

How do I deal with "Error in FUN(X[[i]],..." when trying to add text labels to points with geom_text?

我是 R 的新手。如果您能给我任何帮助,我将不胜感激。

我正在使用 choroplethr 包通过邮政编码创建地图。我想使用 geom_point 添加显示城市的叠加层。

我的密码是

t <- test.map +
  geom_point(data=lookup, aes(x=lat, y=lon), size=2, color="black", inherit.aes=FALSE) + 
  geom_text(aes(label=name),hjust=0, vjust=0)

其中 test.map 是来自 choroplethr 的图,lookup 是包含纬度 (lat)、经度 (lon) 和位置名称 (name) 的数据框。

geom_text returns 错误:

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

我不知道为什么。

你能帮帮我吗?

谢谢!

OP 代码的问题在于 geom_pointgeom_text 继承了用于创建 test.map

的数据和美学

如果我们想为附加层使用不同的数据集,我们需要在每个层中指定 data 参数,并将 inherit.aes 设置为 FALSE

test.map +
  geom_point(data=lookup, aes(x=lat, y=lon), size=2, color="black", inherit.aes=FALSE) +
  geom_text(data=lookup, aes(label=name), hjust=0, vjust=0, inherit.aes=FALSE)