Skip to content

Instantly share code, notes, and snippets.

@jebyrnes jebyrnes/geospatial_test.R
Last active Jan 22, 2019

Embed
What would you like to do?
Try this and make sure there are no errors. If it all runs, you're in good shape! Should make three plots, and install rnaturalearth, which is pretty cool
#'------------------------------
#'
#' Script to make sure everything works
#' for you for the 2019-01-22 Geospatial
#' Data Carpentry workshop at UMB
#'------------------------------
# Make sure we have rnaturalearth installed
# If you do, comment out the install.packages line
#or just don't run it.
install.packages("rnaturalearth")
library(rnaturalearth)
## STOP HERE - THEN RUN THE NEXT LINE ON ITS OWN
## AS IT WILL GIVE YOU A SERIES OF PROMPTS TO WALK THROUGH
install_rnaturalearthdata()
## OK - AS LONG AS THAT WORKED.....
# The SF library and ggplot
# If you get a package not found error, try typing
# install.packages("PACKAGENAME")
library(sf)
library(ggplot2)
library(rgeos)
#get the countries of the world
countries <- ne_countries(returnclass="sf")
#plot them
ggplot() +
geom_sf(data = countries, fill = "lightgreen")
#### Run to this point, then stop and make sure you have a map,
#### Then....try what is below
#A raster test
library(raster)
#Test a raster
rst <- ne_download(scale = 50, type = 'MSR_50M', category = 'raster', destdir = getwd())
# load after having downloaded
rst <- ne_load(scale = 50, type = 'MSR_50M', category = 'raster', destdir = getwd())
#aggregate - this might take a while
rst_agg <- aggregate(rst, fact = 50, fun = mean)
# plot
plot(rst_agg)
#### Run to this point, then stop and make sure you have a map,
#### Then....try what is below
rst_df <- as.data.frame(rst_agg, xy=TRUE)
#Plot shapefile and raster together!
ggplot() +
geom_raster(rst_df, mapping = aes(x = x, y = y, fill = MSR_50M)) +
geom_sf(data = countries, color = "black", fill = NA)
#### Run to this point, then stop and make sure you have a map
# Make sure these libraries load with no errors
# If you get a package not found error, try typing
# install.packages("PACKAGENAME")
# at the prompt and following any instructions -
# and if there are any errors, email us
library(rgdal)
library(rasterVis)
library(remotes)
library(tmap)
@DrK-Lo

This comment has been minimized.

Copy link

commented Jan 21, 2019

need to install "rgeos" before you can run countries <- ne_countries(returnclass="sf")

@DrK-Lo

This comment has been minimized.

Copy link

commented Jan 22, 2019

ggplot() +
geom_raster(rst_df, mapping = aes(x = x, y = y, fill = MSR_50M)) +
geom_sf(data = countries, color = "black", fill=NA)

@DrK-Lo

This comment has been minimized.

Copy link

commented Jan 22, 2019

also if you have problems with plot(rst_agg) because your figure margins are too large, you can run par(mfrow=c(1,1), mar=c(0,0,0,0)) first

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.