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]
}

Advertisement
This entry was posted in Uncategorized. Bookmark the permalink.