I am trying to add district labels for a country, which I am plotting using levelplot (to use worldclim precipitation data) and adding boundaries using spplot.

I am having trouble adding text labels of the districts onto the map. I have the following code:

tan <- getData("GADM", country="Tanzania", level=1)
alt_world <-getData('worldclim', var='alt', res=10)

tanalt.sub <- crop(alt_world, extent(tan))
tan.sub <- mask(tanalt.sub, tan)

p1 <- levelplot(tan.sub, col.regions=colorRampPalette(brewer.pal(9, 'Blues')),margin=FALSE,main ='Tanzania rainfall (mm/year)')
p2 <- spplot(tan)

p <- p1+p2

I have tried the following to add labels:

labels <- layer(sp.text(coordinates(tan), txt = tan$NAME_1, pos = 1))
p2 <- p2 + labels

But get an error regarding 'inherited function for coordinates'.


Managed to solve it using ggplot2, however still looking at how to use labels with levelplot.

tan.adm.spdf <- getData("GADM", country="Tanzania", level=1)
tan.adm.df <- fortify(tan.adm.spdf, region="NAME_1")

tan.adm.centroids.df <- data.frame(long = coordinates(tan.adm.spdf)[, 1],lat = coordinates(tan.adm.spdf)[, 2]) 
tan.adm.centroids.df[, 'NAME_1'] <- tan.adm.spdf@data[, 'NAME_1']

alt_world <-getData('worldclim', var='alt', res=2.5)
tanalt.sub <- crop(alt_world, extent(tan.adm.spdf))
tan.sub <- mask(tanalt.sub, tan)

test_spdf <- as(tan.sub, "SpatialPixelsDataFrame")
test_df <- as.data.frame(test_spdf)
colnames(test_df) <- c("value", "x", "y")

p <- ggplot() + geom_tile(data=test_df, aes(x=x, y=y, fill=value), alpha=0.8) + geom_polygon(data=tan.adm.spdf, aes(x=long, y=lat, group=group),fill=NA, color="black", size=0.90) + geom_text_repel(data = tan.adm.centroids.df, aes(label = NAME_1, x = long, y = lat, group = NAME_1), size = 3)

Edit, found a solution:

tan.adm.labels <- SpatialPoints(tan.adm.centroids.df[,c("long", "lat")])
p1 <- levelplot(tan.sub, col.regions=colorRampPalette(brewer.pal(9, 'Blues')),margin=FALSE,main ='Tanzania rainfall (mm/year)', alpha=0.5) + layer(sp.points(points, pch=21,col="black", fill='red',cex=0.95, alpha=0.7)) + spplot(tan.adm.spdf, alpha=0.7, col='#808080') + layer(sp.text(coordinates(tan.adm.labels), txt = tan.adm.centroids.df$NAME_1), scale=0.5)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.