How to create unique labels for multiple rows in geom_text?

心不动则不痛 提交于 2019-12-11 06:43:40

问题


I have a data frame like this

zip   state  users  longitude latitude
00501  NY    1000   -72.63708 40.92233
00544  NY    1000   -72.63708 40.92233
00601  PR    2000   -66.74947 18.1801
00602  PR    2000   -67.18024 18.36329

I'm plotting number of users using ggmap and geom_point.

map<-get_map(location='united states', zoom=4, maptype = "terrain",
         source='google',color='color')
ggmap(map) + geom_point(
aes(x=longitude, y=latitude, show_guide = TRUE, colour=users), 
data=data, alpha=.5, na.rm = T)  + 
scale_color_gradient(low="red", high="green")

The plot comes out to be like this

Now I'm trying to create labels for all states using geom_text.

map<-get_map(location='united states', zoom=4, maptype = "terrain",
         source='google',color='color')
ggmap(map) + geom_point(
aes(x=longitude, y=latitude, show_guide = TRUE, colour=users), 
data=data, alpha=.5, na.rm = T)  + 
scale_color_gradient(low="red", high="green")  +
geom_text(aes(x = longitude, y = latitude, label = as.character(state)), 
data = data,inherit.aes = FALSE)

The plot comes out to be like this.

Labels are created for each row. How to create unique label for multiple rows?

Edit: One way to do this is to remove duplicate state names from the data itself. Is there a more efficient way?


回答1:


The easiest solution is to aggregate your data into a new dataframe first:

agg.data <- aggregate(cbind(longitude,latitude) ~ state, data = data, mean)

and then use the aggregated data to include the text labels:

ggmap(map) + 
  geom_point(data = data, 
             aes(x = longitude, y = latitude, show_guide = TRUE, colour=users), 
             alpha = 0.5, na.rm = T)  + 
  scale_color_gradient(low = "red", high = "green")  +
  geom_text(data = agg.data, 
            aes(x = longitude, y = latitude, label = as.character(state)))


来源:https://stackoverflow.com/questions/41800430/how-to-create-unique-labels-for-multiple-rows-in-geom-text

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