在R中为地图上的数据点添加标签

3

我创建了一个地图,标出了我的数据点。我希望:

  • 城市名称更加清晰可见,可以上下移动。
  • 给数据点标上1-7的标签,让数字显示在顶部。

这是我的数据集和我的操作:

library("ggplot2")
theme_set(theme_bw())
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")

stations <- data.frame(longitude = c(-58,-54,-50,-44.95,-40,-35.87,-31), latitude = c(22,22,22,23.367,23,22.33,22))

world <- ne_countries(scale = "medium", returnclass = "sf")
class(world)

world_points<- st_centroid(world)
world_points <- cbind(world, st_coordinates(st_centroid(world$geometry)))

a <- world_points[50,]
b <- world_points[34,]
cities <- rbind(a,b)

ggplot(data = world) +
    geom_sf() +
  geom_text(data= cities,aes(x=X, y=Y, label=name),
    color = "black", fontface = "bold", check_overlap = FALSE) +
annotate(geom = "text", x = -90, y = 26, label = "Gulf of Mexico", 
    fontface = "italic", color = "grey22", size = 6) +
    geom_point(data = stations, aes(x = longitude, y = latitude), size = 4, 
        shape = 21, fill = "red") +
    coord_sf(xlim = c(-80, -10), ylim = c(10, 30), expand = FALSE)
2个回答

2
这里介绍了一种使用ggrepel包中的geom_text_repel方法的技术。
library("rgeos")
library("ggrepel")
ggplot(data = world) + geom_sf() + 
  geom_text_repel(data= cities,aes(x=X, y=Y, label=name), fontface = "bold",nudge_x = c(-5,5), nudge_y = c(-3,5)) +
  geom_point(data = stations, aes(x = longitude, y = latitude), size = 4, shape = 21, fill = "red") +  
  geom_text_repel(data= stations,aes(x=longitude, y=latitude, label=1:7), fontface = "bold",nudge_x = 1, nudge_y = 1) +
  coord_sf(xlim = c(-80, -10), ylim = c(10, 30), expand = FALSE)

enter image description here


谢谢大家,非常有帮助! - Ecg

2

使用 ggrepel,您可以让城市名称略微偏离其位置。要为您的站点添加标签,可以使用带有参数 labelgeom_text

总体来说,它可能是这样的:

library(ggrepel)
ggplot(data = world) +
  geom_sf() +
  geom_text_repel(data= cities,aes(x=X, y=Y, label=name),
            color = "black", fontface = "bold") +
  annotate(geom = "text", x = -90, y = 26, label = "Gulf of Mexico", 
           fontface = "italic", color = "grey22", size = 6) +
  geom_point(data = stations, aes(x = longitude, y = latitude, label = 1:7), size = 4, 
             shape = 21, fill = "red") +
  coord_sf(xlim = c(-80, -10), ylim = c(10, 30), expand = FALSE)+
  geom_text(data = stations,aes(x = longitude, y = latitude, label = 1:7), size = 4, 
            shape = 21, fill = "red", vjust = -1)

enter image description here


哇,我花了这么长时间,结果还迟到了 11 秒。干得好。 - Ian Campbell
1
哈哈哈 ;) 我在另一篇帖子上也遇到了同样的问题。我想使用 nudge 部分来改进 geom_text_repel,但你先抢了,那就算平局吧 :D - dc37

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接