Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Label datapoints in a map in R

Tags:

r

ggplot2

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)
like image 336
Ecg Avatar asked Sep 13 '25 09:09

Ecg


1 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

like image 132
dc37 Avatar answered Sep 14 '25 23:09

dc37