How to plot coordinates on top of a world map and change xlim values?

31 Views Asked by At

I need to flip my x-axis lim from (-71.0,-69.5) to (-69.5,-71.0). I also need to add a world map to display my points onto.

This is my current line of code.

library(ggplot2)
library(readxl)

#Upload dataset
setwd("Behavior Data/STATE_SPACE_MODEL_SCRIPT/")
data <- read_excel("234798 ssm.xlsx")
View(data)

plot <- ggplot(data, aes(x=lon, y=lat, color=b),xlim=(c(-69.5, -71)) +
  geom_point(size=2) 
plot
*

xlim in this context does nothing. Als,o I want to overlay my plot onto a world map.

enter image description here

1

There are 1 best solutions below

0
Till On

Make sure that the following packages are installed. If in doubt install them with:

# install.packages(c("sf", "rnaturalearth", "rnaturalearthdata"))
library(tidyverse)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)

Get the gemetry data for the world map.

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

Create some random coordinates. Use sf::st_as_sf() to turn them into an sf object with the same crs of world.

points <- 
  tibble(
    lon = sample(-180:180, 10),
    lat = sample(-90:90, 10)
  ) |> 
  st_as_sf(coords = c("lon", "lat"),
           crs = st_crs(world))

Plot the world map with points on top.

ggplot() +
  geom_sf(data = world, fill = "black") +
  geom_sf(data = points, color = "yellow")

Plot the world map with points on top and set xlim to specific values

ggplot() +
  geom_sf(data = world, fill = "black") +
  geom_sf(data = points, color = "yellow") +
  coord_sf(xlim = c(-60, 70))