Search code examples
rggplot2geospatial

Adding earthquake data and map for Fiji


I used the datasets::quakes to plot the earthquakes on Fiji like that:

quakes_df <- datasets::quakes
library(ggplot2)
my_plot <- ggplot() +
  geom_point(data= quakes_df, aes(lat, long, col= mag)) +
  scale_color_gradient(low= "green", high= "red", na.value= "black", aesthetics= "colour", 
                   breaks= seq(min(quakes_df$mag), max(quakes_df$mag), length.out= 4))
my_plot

earthquakes

In the next step I want to add the polygons for Fiji in order to better understand where the earthquakes actually happen. But so far I cant figure out how to combine both plots. What I do is:

# Data of whole world
world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")
# Extract Fiji only.
fiji <- subset(world, sovereignt == "Fiji", select= "geometry")
# Add new layer to existing plot
my_plot + geom_sf(data= fiji)

wrong

The resulting plot is wrong. What is happening here? And how can I add Fijis country borders onto the first plot with the earthquakes?


Solution

  • You can use the package sf to transform your dataframe as a geospatial object sf ex. with sf::st_as_sf(). The data seems to be expressed in longitude-latitude; probably in the coordinate reference systeme (CRS) EPSG:4326 . Since it's around the 180­deg line, this answer suggest to use the CRS EPSG:3994 (disclamer: I am not familiar with the CRS of the Pacific area).

    I added Australia on the map for more spatial context.

    library(sf)
    library(tidyverse)
    
    quakes_df <- datasets::quakes
    world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")
    fiji <- subset(world, sovereignt == "Fiji", select= "geometry")
    Australia <- subset(world, sovereignt == "Australia", select= "geometry")
    
    quakes_sf <- st_as_sf(quakes_df , coords =c ("long","lat") , crs = 4326) %>% 
      st_transform(crs=3994)
    
    ggplot() +
        geom_sf(data= fiji %>% st_transform(crs=3994))+
      geom_sf(data= Australia %>% st_transform(crs=3994))+
      geom_sf(data= quakes_sf, aes(col= mag),alpha = 0.2) +
      scale_color_gradient(low= "green", high= "red", na.value= "black", aesthetics= "colour", 
                           breaks= seq(min(quakes_df$mag), max(quakes_df$mag), length.out= 4))
    

    Created on 2024-07-10 with reprex v2.1.0