29 Jun 2012

Use IUCN API with R & XPath

Thanks to a posting on R-sig-eco mailing list I learned of the IUCN-API. Here's a simple example for what can be done with it (output as pdf is HERE):


input = "panthera-uncia"
h <- htmlParse(paste("http://api.iucnredlist.org/go/",
               input, sep = ""))

distr1 <- xpathSApply(h, '//ul[@class="countries"]', xmlValue)
distr2 <- unlist(strsplit(distr1, "\n"))
distr2[distr2 == "Russian Federation"] <- "Russia"

pop <-xpathSApply(h, '//div[@id="population"]/text()[preceding-sibling::br]', xmlValue)
status <- xpathSApply(h, '//div[@id="red_list_category_code"]', xmlValue)


pdf("IUCN_map.pdf", width = 10, height = 10, pointsize = 20)
par(mar = c(3, 3, 1, 1))
plot(wrld_simpl, col = "grey98", xlim=c(-170, 170), axes = T)
plot(wrld_simpl[wrld_simpl$NAME %in% distr2,], col = "grey75", add = T)
text(0, 150, gsub("-", " ", toupper(input)), font = 3)
text(0, 130, paste("--Status: ", status, "--", sep = ""))
text(0, -98, "--Population--", cex = 0.5, font = 2) 
text(0, -140, paste(strwrap(pop, width = 30), collapse = "\n"), cex = 0.4)

# download image:
myjpg <- paste(tempdir(), "/", input, ".jpg", sep = "")
              myjpg, mode = "wb")

# read and plot image:
img <- readJPEG(myjpg)
w <- dim(img)[2]/7
h <- dim(img)[1]/7

# print img to plot region:
rasterImage(img, 115, 95, 115+w, 95+h)

ps: Check THESE nice maps, too!


  1. Replies
    1. Edi, thanks again for your valuable posting to r-sig-eco - I knew of the great IUCN Red List site but not ot of its API..

  2. Nice demonstration! But you should choose colours wisely in future - with the light grey on white the map is unreadable and it makes it useless... Note that Russia is as white as Australia while there are at least several dozens of these cats. Also from cartographer's point of view with the given map's name one will expect to see a natural habitat, not the countries having cats ;-)

    1. Of course! But you see, this is just a simple demo for getting started..

    2. Sure))) Good luck with that!

    3. I did change the color (a bad choice indeed). And you were obviously right with 'Russia' which didn't match 'Russian Federation' and was thus missed in the map.. Thanks for that hint!

  3. yes-yes-yes-yes! I love this

    a-we-so-me, thanks!