Error: Aesthetics must be either length 1 or the same as the data (4)

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

I am working with ggmap. the goal is to plot coordinate points on the map and label the points with their names. I have data frame with name, longitude and latitude.

The data looks like:

df <- structure(list(Station.Area = c("Balbriggan", "Blanchardstown",  "Dolphins Barn", "Donnybrook", "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") 

The code I wrote is as below:

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() 

But i am getting

Error: Aesthetics must be either length 1 or the same as the data (4): label

I have tried to put various aesthetics in geom_text like size,color,x & Y but it still gives out same error.

Am i doing it correctly for my goal? Please help.

Getting this without geom_text now I just want to label the points

回答1:

There are a couple of things not quite right in your code.

For the geom_point you only want the x and y in your aes. The other arguments should be outside, giving

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

Also the label for the geom_text should be inside aes. However, as there is no data, x or y at a higher level, then geom_text will not find the label variable or the positions of where to place the labels. So you also need to include these in the call

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

However, you can omit some of this repetition by using the base_layer argument of 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()  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!