Visualizing GIS data with R and Open Street Map

Reading time ~1 minute

In this post I way to share with you some code to use Openstreetmap - maps as a backdrop for a data visualization. We will use the RgoogleMaps-package for R. In the following I will show you how to make this graph.

1. Download the map

I wanted to take a closer look at an area around my former neighborhood, which is in Bochum, Germany.

lat_c<-51.47393 lon_c<-7.22667 bb<-qbbox(lat = c(lat_c[1]+0.01, lat_c[1]-0.01), lon = c(lon_c[1]+0.03, lon_c[1]-0.03))

Once this is done, you can download the corresponding Openstreetmap tile with the following line.<-GetMap.OSM(lonR=bb$lonR, latR=bb$latR, scale = 20000, destfile="bochum.png")

2. Add some points to the graphic

Now your second step will most likely be adding points to the map. I choose the following two.

lat <- c(51.47393, 51.479021) lon <- c(7.22667, 7.222526) val <- c(10, 100)

As the R-package was mainly build for google-maps, the coordinates need to be adjusted by hand. I made the following functions, that take the min and max value from the downloaded map.

lat_adj<-function(lat, map){(map$BBOX$ll[1]-lat)/(map$BBOX$ll[1]-map$BBOX$ur[1])} lon_adj<-function(lon, map){(map$BBOX$ll[2]-lon)/(map$BBOX$ll[2]-map$BBOX$ur[2])

Now you can add some points to the map. If you want them to mean anything it may be handy to specify an alpha-level and change some aspects of the points, e.g. size, color, alpha corresponding to some variable of interest.

PlotOnStaticMap(, lat = lat_adj(lat,, lon = lon_adj(lon,, col=rgb(200,val,0,85,maxColorValue=255),pch=16,cex=4)

Here is the full code:


#define the part of the world you want to plot. Here the area around my former home.
bb<-qbbox(lat = c(lat_c[1]+0.01, lat_c[1]-0.01), lon = c(lon_c[1]+0.03, lon_c[1]-0.03))

# download the tile from OSM<-GetMap.OSM(lonR=bb$lonR, latR=bb$latR, scale = 20000, destfile="bochum.png")
#Add some coordinates
lat<- c(51.47393, 51.479021)
lon<- c(7.22667, 7.222526)
val <- c(0, 255)

#function to adjust the coordinates
lat_adj<-function(lat, map){(map$BBOX$ll[1]-lat)/(map$BBOX$ll[1]-map$BBOX$ur[1])}
lon_adj<-function(lon, map){(map$BBOX$ll[2]-lon)/(map$BBOX$ll[2]-map$BBOX$ur[2])}

PlotOnStaticMap(, lat = lat_adj(lat,, lon = lon_adj(lon,, col=rgb(255,0, val,90,maxColorValue=255),pch=16,cex=4)

dev.print(jpeg,"test.jpeg", width=1204, height=644, units="px")

The world is flat F(1,18) = 39.200; p = .335 - or p < .01 or p <.001? - Check your stats!

A reviewers dream has come true. The new __statcheck__-package for [R]( automagically checks the accurate __reporting__ of ...… Continue reading


Published on June 19, 2015

Relaunch on Jekyll

Published on June 04, 2015