Stamen maps with spplot

(This article was first published on Omnia sunt Communia! » R-english, and kindly contributed to R-bloggers)

Several R packages provide an interface to query map services (Google Maps, Stamen Maps or OpenStreetMap) to obtain raster images from them. As far as I know, there are three packages devoted to this task: RgoogleMaps, OpenStreetMap and ggmap. The latter two are increasingly popular with a wide collection of providers.

Both of them use the background image to configure the graphical window defining functions (automap and ggmap, respectively) to display the images with ggplot2. Additional information can be layered upon this background image with ggplot2 functions. In my opinion, this approach is somewhat strange. I feel more comfortable with the approach implemented in the spplot function of the sp package, which relies on the main data to be displayed to configure the graphical window instead of using an auxiliary image as the starting point.

Although none of these two packages include functions to work with spplot, it is not difficult to build a mixed solution. The key point is that the result of their queries is mainly a raster image which can be easily displayed with the grid.raster function after some corrections.

The next code displays the location of the photovoltaic systems installed in California grouped by nominal power using data available from the OpenPV project. The procedure is:

• Download an image from the Stamen Maps service according to the spatial extent of the data (this example uses ggmap but a similar approach can be followed with the OpenStreetMap package).
• Use grid.raster to display the image using the coordinates of its corners to define the width, height and center location.
• Display the variable with circles of different sizes and colours over the background image.