Search code examples
rggplot2raster

why ggplot and geom_tile create lines on the map?


Data: https://github.com/yuliaUU/data/blob/main/test.csv

griddf <- read_csv("test.csv")

create a map:

world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")  # add continents
ggplot()+
         geom_tile(data = Data |> dplyr::filter(Model.1=="RF"), aes(x = Lon, y = Lat, fill= value/1000))+geom_sf(data=world)+
            viridis:: scale_fill_viridis(option = "H", na.value = NA) +
            labs(fill="Probability")+
            facet_wrap(~ Model.1)

My issue is that it creates a map with "lines" which I do not understand why. I know it has something to do with irregular grid I am using ( all grid cell should be equal area)

2

and when I add different projection:

+  coord_sf(crs = '+proj=moll')

I get nothing plotted

1


Solution

  • You basically answered the question yourself - your data is too granular. For a more "complete" look, you might want to 2d-interpolate the values. Here, I am using akima::interp, but there are other functions out there - this is not the place to discuss which is the best to use.

    library(ggplot2)
    griddf <- read.csv(url("https://raw.githubusercontent.com/yuliaUU/data/main/test.csv"))
    
    world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")  # add continents
    
    val_interpol <- with(griddf, akima::interp(Lon, Lat, value, xo = -180:180, yo = -90:90))
    #> Warning in akima::interp(Lon, Lat, value, xo = -180:180, yo = -90:90): collinear
    #> points, trying to add some jitter to avoid colinearities!
    #> Warning in akima::interp(Lon, Lat, value, xo = -180:180, yo = -90:90): success:
    #> collinearities reduced through jitter
    ## thanks Akrun https://stackoverflow.com/q/58123551/7941188
    ## matrix doesn't allow negative values for subsetting
    d1 <- expand.grid(x = 1:361, y = 1:181) 
    out <- transform(d1, z = val_interpol$z[as.matrix(d1)])
    out$x <- out$x-181
    out$y <- out$y-91
    
    ggplot()+
      geom_raster(data = out , aes(x = x, y = y, fill= z), interpolate = TRUE)+
      geom_sf(data=world)+
      labs(title=paste0("Swordfish Probability of Occurance"), 
           x="", y="", subtitle="data from 2000-present (0.5x0.5 grid)")+
      viridis:: scale_fill_viridis(option = "H", na.value = "black") 
    

    Created on 2022-05-06 by the reprex package (v2.0.1)