When making many plots of the same dataset, it's often usually to supplement them with same extra information. In this example, we will create a function to add standard elements to a plot illustrated with the JSM 2006 Data expo data.
You can load the data with load("http://had.co.nz/ggplot/examples/ozone.rda"). It contains one data frame, slopes with rates of change of ozone levels on a 24 x 24 grid. We want a general way to supplement the ozone data with a map of the area.
First we will get a map for the region. You will need to have the maps library installed for this to work.
> library(maps)
> reg <- as.data.frame(map("world", xlim = -c(113.8, 56.2), ylim = c(-21.2,
36.2), plot = FALSE)[c("x", "y")])
We'll plot this, just to make sure it looks ok:
> qplot(x, y, data = reg, type = "path")![]()
Yup, that looks good.
We will display the data with a simple bubbleplot:
> load("ozone.rda")
> ggpoint(ggplot(slopes, aes = list(x = long, y = lat, size = abs(value),
colour = sign(value))))
To overlay the map on this, we are going to need to do things step by step, rather than using qplot. First, we create a ggplot object with the correct defaults for displaying the ozone data, then we add a grob function to draw the map, and then the points.
> p <- ggplot(slopes, aes = list(x = long, y = lat))
> p <- ggpoint(p, aes = list(size = abs(value), colour = sign(value)),
data = slopes)
> p <- ggpath(p, data = reg, aes = list(x = x, y = y))
> p
You can see how this could be easily turned into a function that takes a ggplot object and adds a map on top. The following does exactly that, as well as adding some scales to ensure only the correct zone is shown.
> addmap <- function() {
p <- ggpath(p, data = reg, aes = list(x = x, y = y), colour = alpha("grey20",
0.6))
p <- pscontinuous(p, "x", range = -c(113.8, 56.2))
p <- pscontinuous(p, "y", range = c(-21.2, 36.2))
p
}