【问题标题】:Error: Aesthetics must be either length 1 or the same as the data (4)错误:美学必须是长度 1 或与数据相同 (4)
【发布时间】:2025-11-25 23:35:02
【问题描述】:

我正在与ggmap 合作。目标是在地图上绘制坐标点并用它们的名称标记这些点。我有名称、经度和纬度的数据框。

数据如下:

df <- structure(list(Station.Area = c("Balbriggan", "Blanchardstown", 
"Dolphins Barn", "Donny*", "Dun Laoghaire", "Finglas"), Latitude = c(53.608319, 
53.386813, 53.333532, 53.319259, 53.294396, 53.390325), Longitude = c(-6.18208, 
-6.377197, -6.29146, -6.232017, -6.133867, -6.298401)), .Names =c("Station.Area","Latitude", "Longitude"), row.names = c(NA, 6L), class = "data.frame")

我写的代码如下:

library(ggmap)
library(ggplot2)

dub_map <- get_map(location = "Dublin", zoom = "auto", scale="auto", crop = TRUE, maptype = "hybrid")

ggmap(dub_map) +`
    geom_point(data = df, aes(x = Longitude, y = Latitude, 
              fill = "green", alpha =` `0.8, size = 5, shape = 21)) +`
guides(fill=FALSE, alpha=FALSE, size=FALSE)+
geom_text(label=df$Station.Area)+
scale_shape_identity()

但我得到了

错误:美学必须是长度1或与数据相同(4):标签

我尝试在geom_text 中加入各种美学元素,例如尺寸、颜色、x 和 Y,但仍然会出现相同的错误。

我是否正确地实现了我的目标?请帮忙。

在没有 geom_text 的情况下得到这个我只想标记点

【问题讨论】:

  • 不知道你要不要geom_text(aes(label=Station.Area))。也不要像aes 中那样调整大小、alpha 等 - 在外面做
  • 是的,我想使用相同的,但是当我在没有 df$ 的情况下运行代码时,它无法识别该列。
  • 好的,你能分享一些你的数据吗?如果是这样,您可以使用dput(head(df)) 的结果编辑您的问题吗?
  • 站区域纬度经度巴尔布里根53.608319 -6.18208布兰53.386813 -6.377197海豚谷仓53.333532 -6.29146东尼布鲁克53.319259 -6.232017敦劳海尔53.294396 -6.133867 Finglas 53.390325 -6.298401 Kilbarrack 53.383747 -6.15254北钢绞线53.358192 -6.240886 Phibsborough 53.359906 - 6.2724 Rathfarnham 53.300498 -6.283854 Skerries 53.580552 -6.107878 Swords 53.455747 -6.219741 Tallaght 53.288804 -6.355706 Tara St 53.3473 -6.2549
  • 完美!!再次感谢!

标签: r ggplot2 ggmap geom-text


【解决方案1】:

您的代码中有几处不太正确。

对于geom_point,您只需要aes 中的xy。其他论据 应该在外面,给

geom_point(data = df, aes(x = Longitude, y = Latitude), 
                  fill = "green", alpha =0.8, size = 5, shape = 21)

另外,geom_textlabel 应该在 aes 内。然而, 因为没有更高级别的dataxy,所以geom_text 将找不到标签变量或放置标签的位置。所以你还需要在调用中包含这些

geom_text(data=df, aes(x = Longitude, y = Latitude, label=Station.Area))

但是,您可以使用 base_layer 参数省略部分重复 ggmap:

ggmap(dub_map, 
      base_layer = ggplot(data=df, aes(x = Longitude, 
                                       y = Latitude, 
                                       label=Station.Area))) +
      geom_point(fill = "green", alpha =0.8, size = 5, shape = 21) +
      geom_text() 

【讨论】:

    最近更新 更多