如何在geom_text中为多行创建唯一标签?

时间:2017-01-23 06:30:01

标签: r plot ggplot2 ggmap geom-text

我有一个像这样的数据框

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

我正在使用ggmap和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")

情节就是这样的 enter image description here

现在我尝试使用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)

情节就是这样的。 enter image description here

为每一行创建标签。如何为多行创建唯一标签?

编辑:执行此操作的一种方法是从数据本身中删除重复的状态名称。有更有效的方法吗?

1 个答案:

答案 0 :(得分:2)

最简单的解决方案是首先将数据汇总到新的数据框中:

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

然后使用汇总数据来包含文本标签:

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