【问题标题】:How to create unique labels for multiple rows in geom_text?如何为 geom_text 中的多行创建唯一标签?
【发布时间】:2017-01-23 06:30:01
【问题描述】:

我有一个这样的数据框

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

剧情是这样的

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

剧情变成了这样。

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

编辑:一种方法是从数据本身中删除重复的州名。有没有更有效的方法?

【问题讨论】:

    标签: r plot ggplot2 ggmap geom-text


    【解决方案1】:

    最简单的解决方案是先将您的数据聚合到一个新的数据框中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      相关资源
      最近更新 更多