Label datapoints in a map in R

Viewed 191

I have created a map plotting my datapoints, I would like:

  • That the city names are more visible or move them up or down so
  • To label the datapoints 1-7 so the numbers appear on top.

Here is my dataset and what I have done:

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 Answers

Using ggrepel, you can get the cities names being a little bit out of their locations. For labelling your stations, you can add a geom_text with the parameter label.

Altogether, it can be something like that:

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

Here is an approach with geom_text_repel from the ggrepel package.

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

Related