R functions

I am constantly re-googling a lot of functions. Here they are in one place.

Plotting a world map over data in ggplot:

“`{r worldmap}
# load libraries:
library(ggplot)

# get a map of the world:
worldmap <- map_data(“world”)

# define a custom theme for prettier plots:
my_map_theme <- function () {
theme_bw() %+replace%
theme(
panel.background = element_rect(fill = “lightblue”),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = “black”),
axis.text.x = element_text(size = 12, angle = 45, hjust = 1),
axis.text.y = element_text(size = 12),
strip.text.x = element_text(size = 12, colour = “black”, angle = 0),
axis.title.x=element_text(size=12),
axis.title.y=element_text(size=12)
)
}

# make some fake data:
n=100
NLlons <- sample(x=seq(from=3, to=7, by=0.001), size=n, replace=TRUE)
NLlats <- sample(x=seq(from=51, to=54, by=0.001), size=n, replace=TRUE)
pointdata <- data.frame(value=rnorm(n, mean=15, sd=5), lon=NLlons, lat=NLlats)

# make a plot:
ggplot(pointdata) +
# TO PLOT THE MAP
geom_polygon(data = worldmap, aes(x=long, y = lat, group = group), fill = “white”, color = “black”) +
# TO PLOT THE POINTS
geom_point(aes(x=lon, y=lat, color=value)) +
# USE A NICER THEME
my_map_theme() +
# CHANGE THE COLOR OF THE POINTS
scale_colour_gradientn(colors=terrain.colors(10)) +
# ZOOM IN ON THE REGION OF INTEREST
coord_fixed(xlim = c(floor(min(pointdata$lon, na.rm = TRUE)), ceiling(max(pointdata$lon, na.rm = TRUE))),
ylim = c(floor(min(pointdata$lat, na.rm = TRUE)), ceiling(max(pointdata$lat, na.rm = TRUE))))

“`

Listing objects by size:

“`{r objectsize}
# Thanks stackoverflow!
# (https://stackoverflow.com/questions/1395270/determining-memory-usage-of-objects)

sort(sapply(ls(),function(x){ print(object.size(get(x)), units = “auto”)}))

“`

Rotating axis labels in ggplot2:

theme(axis.text.x = element_text(angle = 90, hjust = 1))

Pad leading zeros:

sprintf(“%03d”, 0:10)

 

Getting nice colours:

gg_color_hue <- function(n) {
# ggplot colors
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}

Advertisements
Posted in Uncategorized

Plants of the Shoalhaven Region

https://plantid.shinyapps.io/posr/

https://kiriwhan.shinyapps.io/posr/

POSR is an online tool to aid in the identification of plants in the Shoalhaven region on the south-coast of NSW, Australia. Written in the R Statistical Computing Environment and powered by shinyapps.io, the website is multi-platform running in any web browser or on your smart phone or tablet in the field.

This online tool is a lite version of the standalone Plants of the Shoalhaven Database (http://www.presoz.com.au/posr/welcome.html). The database was originally designed to help the Milton Rural Landcare Group (http://www.presoz.com.au/landcare/welcome.html) identify local plant species, the website will be a valuable field resource for landcarers, botanists and plant enthusiasts from the South-Coast.

 

Posted in Uncategorized