2

I have a dataset of several thousand geographical points, each assigned a cluster (in my reproducible example below I simplify this to 8 points). I want to color an entire global map (only the landmass) using k nearest neighbours to these points. I want to visualise the map using leaflet in r (ultimately for a shiny app). I can plot the results ok using ggplot, but run into some problems when using leaflet. The problems are

  1. The raster doesn't cover all of the antarctic in the leaflet map (I assume I need to use a different dataset than wrld_smpl to mask the raster, but have not succeeded in doing so).
  2. Whereever two different clusters meet, there is a gap in the raster coverage
  3. The coastlines are highly pixelated.

I greatly appreciate any guidance on how to tackle this!

Reproducible example:

# ggplot2 approach ###################################################################################

# Randomly generate 8 points with 8 clusterlabels
train = data.frame(lon=runif(8, -180, 180),lat=runif(8,-90,90), clustername=1:8)
train

library(ggplot2)
library(raster)
library(class)
library(maptools) # for wrld_smpl data

# Get data for land borders
data(wrld_simpl)

# Make grid of lat/lon points covering whole world
dfgrid = expand.grid(lon=seq(-180,180,by=.1), lat =seq(-90,90, by=.1))

# Convert to spatial points, specify correct coordinate reference system (CRS), same as wrld_smpl
pts <- SpatialPoints(dfgrid, proj4string=CRS(proj4string(wrld_simpl)))

# Only keep points over land
dfgrid = dfgrid[!is.na(over(pts, wrld_simpl)$FIPS),]

#dfgrid$clusterlabels = 1
# Asign cluster labels using knn
dfgrid$clusterlabels = knn(train=train[,c("lon","lat")],
                        test=dfgrid[,c("lon", "lat")],
                        cl=train$clustername,
                        k=1)

r = rasterFromXYZ(dfgrid, crs =  "+proj=longlat")
r

#plotting
var_df <- as.data.frame(rasterToPoints(r))
p <- ggplot() +
  geom_polygon(data = wrld_simpl[wrld_simpl@data$UN!="10",], 
               aes(x = long, y = lat, group = group),
               colour = "black", fill = "grey") # does the fortification automatically
p <- p + geom_tile(data = var_df, aes(x = x, y = y, fill = as.factor(clusterlabels)))+
  theme(legend.title = element_blank())
p = p + scale_fill_brewer(palette = "Paired")
p


# leaflet approach #############################################################################################

library(leaflet)

pal <- colorFactor("Paired", values(r),na.color = "transparent")

leaflet() %>% addTiles()

leaflet() %>% addTiles() %>%
  addRasterImage(r, colors = pal, opacity = 0.8) %>%
  addLegend(pal = pal, values = values(r),
            title = "Cluster label")

ggplot results

leaflet resutls showing raster gap in antarctica

zoomed in leaflet results showing pixelated coastline and gap between clusters

0

Browse other questions tagged or ask your own question.