How to create unique labels for multiple rows in g

2019-08-01 23:26发布

问题:

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