Drawing polar centered spatial maps using ggplot2

November 8, 2011

(This article was first published on NumberTheory » R stuff, and kindly contributed to R-bloggers)

Drawing maps of the polar regions can be done using square spatial maps. A small example says more than a thousand words:

xlim = c(-180,180)
ylim = c(60,90)
# Some fake grid data
dat_grid = expand.grid(x = xlim[1]:xlim[2], y = ylim[1]:ylim[2])
dat_grid$value = runif(nrow(dat_grid))
# Polygons data
dum = map(xlim = c(-180,180), ylim = c(60,90), plot = FALSE)
ant_ggplot = data.frame(dum[c("x","y")])
ant_ggplot$value = mean(dat_grid$value)
# Make the square spatial map
ggplot(aes(x = x, y = y, fill = value), data = dat_grid) + geom_tile() + 
  geom_path(data = ant_ggplot)

The final call to ggplot results in the following picture:

A much more natural way of plotting this polar centered data would be to use polar coordinates. This is supported by ggplot2 through the coord_polar() command. In code (with great help from Charlotte Wickham) this results in:

res <- 1 # 1 degree resolution
x_cell_lim <- c(180, -180) + c(1, -1) * res/2
y_cell_lim <- c(90, 60) + c(1, -1) * res/2
ggplot(aes(x = x, y = y, fill = value), data = dat_grid) + geom_tile() + 
  geom_path(data = ant_ggplot) + 
  scale_fill_gradient(low = "white", high = muted("red")) + 
  coord_polar(start = -pi/2, expand = FALSE) +
  scale_y_continuous("") + scale_x_continuous("") + 
  xlim(x_cell_lim) + ylim(y_cell_lim) +
  opts(axis.ticks = theme_blank(), axis.text.y = theme_blank(), 
       axis.title.x = theme_blank(), axis.title.y = theme_blank(),
       panel.border = theme_blank())

Note that I use theme_blank() many times to get rid of certain elements of the plot (rectangle around the plot, y-axis etc). In addition, the calls to x_lim and y_lim are necessary. Charlotte Wickham explains (direct quote from ggplot2 mailing list): The little additions to the limits make sure the entire cell in plotted without any gaps. It might make more sense to have: x_cell_lim <- c(180, -180) + c(1, +1) * res/2, assuming cells centered at 180 and -180 longitude are the same. The above call to ggplot resuls in the following plot:

Note that the grid cells are nicely scaled towards the north pole. In my opinion this is a much more effective plot for showing polar oriented data.

To leave a comment for the author, please follow the link and comment on his blog: NumberTheory » R stuff.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , , , ,

Comments are closed.