Skip to content

Instantly share code, notes, and snippets.

View scbrown86's full-sized avatar

Stuart Brown scbrown86

View GitHub Profile
@scbrown86
scbrown86 / diverge0.R
Created May 22, 2017 06:04 — forked from johnbaums/diverge0.R
Plot a rasterVis::levelplot with a colour ramp diverging around zero
diverge0 <- function(p, ramp) {
# p: a trellis object resulting from rasterVis::levelplot
# ramp: the name of an RColorBrewer palette (as character), a character
# vector of colour names to interpolate, or a colorRampPalette.
require(RColorBrewer)
require(rasterVis)
if(length(ramp)==1 && is.character(ramp) && ramp %in%
row.names(brewer.pal.info)) {
ramp <- suppressWarnings(colorRampPalette(brewer.pal(11, ramp)))
} else if(length(ramp) > 1 && is.character(ramp) && all(ramp %in% colors())) {
@scbrown86
scbrown86 / ColoredQuant_ggplot2.R
Created August 30, 2017 04:00 — forked from Rekyt/ColoredQuant_ggplot2.R
Color Quantile from a density in ggplot2 with labeled quantiles
# Script from a density to color quantiles area
# Packages ---------------------------------------------------------------------
library(ggplot2)
library(dplyr)
# Data -------------------------------------------------------------------------
r_data = rnorm(100) # Computes 100 values
r_quant = quantile(r_data, probs = seq(0, 1, 0.1)) # Computes quantiles
@scbrown86
scbrown86 / stratified.R
Last active February 16, 2021 15:29 — forked from mrdwab/stratified.R
Stratified random sampling from a `data.frame` in R
stratified <- function(df, group, size, select = NULL,
replace = TRUE, bothSets = FALSE) {
if (is.null(select)) {
df <- df
} else {
if (is.null(names(select))) stop("'select' must be a named list")
if (!all(names(select) %in% names(df)))
stop("Please verify your 'select' argument")
temp <- sapply(names(select),
function(x) df[[x]] %in% select[[x]])
@scbrown86
scbrown86 / diverge0.R
Created January 28, 2018 00:47 — forked from scipionesarlo/diverge0.R
Plot a rasterVis::levelplot with a colour ramp diverging around zero
diverge0 <- function(p, ramp) {
# p: a trellis object resulting from rasterVis::levelplot
# ramp: the name of an RColorBrewer palette (as character), a character
# vector of colour names to interpolate, or a colorRampPalette.
require(RColorBrewer)
require(rasterVis)
if(length(ramp)==1 && is.character(ramp) && ramp %in%
row.names(brewer.pal.info)) {
ramp <- suppressWarnings(colorRampPalette(brewer.pal(11, ramp)))
} else if(length(ramp) > 1 && is.character(ramp) && all(ramp %in% colors())) {
@scbrown86
scbrown86 / alignTwoGGPlots.R
Created February 8, 2018 04:40
Aligning two ggplots when one has a legend
## Function to align two ggplot objects when 1 has a legend and one doesn't
## Copied from https://stackoverflow.com/a/30414008/1710632 on 2018-02-08
AlignPlots <- function(...) {
LegendWidth <- function(x) x$grobs[[8]]$grobs[[1]]$widths[[4]]
plots.grobs <- lapply(list(...), ggplotGrob)
max.widths <- do.call(unit.pmax, lapply(plots.grobs, "[[", "widths"))
plots.grobs.eq.widths <- lapply(plots.grobs, function(x) {
@scbrown86
scbrown86 / rescale_rasters.R
Last active July 6, 2018 05:09
Functions for rescaling a multiband rasterstack or raster layer to an arbitrary range
# Functions for rescaling layers/stacks
## Cleaned up/edited the source code for sdvmspecies library (https://cran.r-project.org/web/packages/sdmvspecies/index.html)
rescaleLayer <- function(raster.layer) {
new.min <- 0; new.max <- 1 ## change for different output range (e.g. 0-255)
min.value <- cellStats(raster.layer, min, na.rm = TRUE)
max.value <- cellStats(raster.layer, max, na.rm = TRUE)
raster.layer <- new.min + (raster.layer - min.value) * ((new.max - new.min) / (max.value - min.value))
return(raster.layer)
}
@scbrown86
scbrown86 / json_to_geopackage.R
Created June 11, 2018 11:58
geoJSON to multilayer geopackage R
# Convert a GeoJSON object to a geopackage
# Add a second geoJSON object in as a second layer
# https://gis.stackexchange.com/q/223240/24249
library(rgdal)
library(sf)
# Here I open a shapefile, but readOGR can be used to read geoJSON files
nc <- st_as_sf(readOGR(system.file("shape/nc.shp", package = "sf")))
# Code from https://www.uva.nl/en/profile/l/o/e.e.vanloon/e.e.vanloon.html
# Implementation of the MapCurves algorithm (DOI 10.1007/s10109-006-0025-x)
mapcurves <- function(A, B, plotGOF = TRUE) {
## R implementation of the mapcurves goodness of fit measure
## (Hargrove et al. 20006, see full reference below) for comparing
## two categorical maps
##
## usage:
@scbrown86
scbrown86 / bivarRasterPlot.R
Last active March 7, 2024 17:04
Make a bivariate plot using raster data and ggplot2
# The function that produces the colour matrix
colmat <- function(nbreaks = 3, breakstyle = "quantile",
upperleft = "#0096EB", upperright = "#820050",
bottomleft = "#BEBEBE", bottomright = "#FFE60F",
xlab = "x label", ylab = "y label", plotLeg = TRUE,
saveLeg = FALSE) {
# TODO - replace any tidyr, dplyr etc. functions with data.table #
library(tidyverse)
require(ggplot2)
require(classInt)
@scbrown86
scbrown86 / multidimensionalNetCDF.R
Created November 29, 2018 04:53
Create a multivariate, multi-dimension (x,y,t) netCDF file from raster data in R
library(raster)
library(ncdf4)
prec <- getData("worldclim", res = 10, var = "prec")
tmax <- getData("worldclim", res = 10, var = "tmax")
prec
tmax
tmax[] <- tmax[]/10