---
title: "How to displaying the IUCN range of your species on top of an assignment map in IsoriX?"
author: "The IsoriX core team"
date: "`r Sys.Date()`"
output:
  pdf_document: default
  word_document: default
references:
- URL: http://www.iucnredlist.org
  accessed: 15th may 2017
  author:
  - family: IUCN (International Union for Conservation of Nature)
    given: null
  id: IUCN2016
  issued: 2016
  link-citations: yes
  title: Myotis bechsteinii. The IUCN Red List of Threatened Species. Version 2017-1
  type: report
  nocite: |
    @IUCN2016
csl: cite_style2.csl
urlcolor: blue
vignette: |
  %\VignetteIndexEntry{5_Add_IUCN_mask}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, initialization, echo=FALSE, results='hide', message=FALSE}
library(knitr)
library(IsoriX)
# set global options for knitr (if changed, all cashed chunked will be rerun!)
knitr::opts_chunk$set(cache = TRUE, cache.path = "./cache_knitr/", fig.path = "./fig_knitr/",
                      global.par = TRUE, width = "\\linewidth",
                      fig.align = "center", dev = "CairoPNG", dpi = 500)
do.eval <- TRUE ## to check that it does work, put TRUE
```

Welcome to __IsoriX__, this vignette will explain to you how to add a second layer to your assignment map.
This additional layer could for example display the IUCN range of your species.

In this vignette we are using a dataset that contains distribution information on *Myotis bechsteinii* assessed for *The IUCN Red
List of Threatened Species^TM^* (IUCN 2016). We downloaded the data from the IUCN Red List website ([http://www.iucnredlist.org/](http://www.iucnredlist.org/)) for free (after filling a short questionnaire).


# Before starting

## Performing the IsoriX workflow

Because we want to illustrate the IUCN range of a species on top of an assignment map, we need to have proceeded thorough an entire IsoriX workflow including the assignment itself. To do that, we are going to recycle the object `assignment` that we created in the vignette `Workflow`:


```{r, load isoscape, echo=FALSE, message=FALSE, results='hide'}
load("../vignette_workflow/assignment.rda")
```

## Getting the files containing the IUCN range for your species ready

Download the .ZIP file containing the information about the geographical range of your species from the IUCN Red List website ([http://www.iucnredlist.org/](http://www.iucnredlist.org/)). 
The .ZIP file stores the species range as an ESRI shapefile. We assume below that the zip file is present in your working directory. If this is not the case, either change your directory (see ```?setwd()```) or identify your working directory using ```getwd()``` and then move your file .ZIP there.

We first need to unzip the .ZIP file. You can do that outside R, but you can also do that directly within R:

```{r}
unzip("species_14123.zip")
```

If you have unzipped the compressed file successfully, a new folder with a code name corresponding to the species should be present in your working directory and this folder should contain your ESRI shapefile (which consists of a collection of different files):

```{r}
dir("./species_14123")
```


# Adding the additional layer

First, we need to transform the shapefile into a ```SpatialPolygonsDataFrame```. This can be done with the package __rgdal__ which provides the function `readOGR()` to read in shapefiles in R.
We must provide the path to the data as a first argument and the name of the layer as a second one.

```{r shapefile, message = TRUE, warnings = FALSE}
library(rgdal)
myotis_bechsteinii <- readOGR("./species_14123/", "species_14123")
```

If you encounter problems while running `readOGR()`, try to update your gdal library (something that you need to do outside R... and which can be tricky under Windows but that is a story that has nothing to do with __IsoriX__).

The `readOGR()` function will also read the .prj file.  If it exists, you can return the projection as follows:

```{r projection}
proj4string(myotis_bechsteinii)
```

If the shapefile has a different projection than your assignment raster you must project the layer according to the projection of your assignment. You can extract such projection from any raster contained in the assignment object. We will use here the one storing p-values for individuals. Here, the projections do not different between our assignment rasters and the IUCN data, but we can nonetheless perform such a projection to illustrate the code (it just has no effect). This step requires the package __raster__.

```{r reproject}
library(raster)
myotis_bechsteinii <- spTransform(myotis_bechsteinii, crs(assignment$indiv$pv))
```

Now we have created a polygon that shows the IUCN range of our species in the same projection as our assignment.
This could be added to an assignment map to display the boundaries of the species range. In order to mask area outside the range of the species, we need to get the inverse polygon. This step requires the package __rgeos__.

```{r create mask}
library(rgeos)
limits <- as(extent(assignment$indiv$pv)+5, "SpatialPolygons")
proj4string(limits) <- crs(assignment$indiv$pv)
iucnmask <- gDifference(limits, myotis_bechsteinii)  
```

We need to pass our ```SpatialPolygons``` in the first mask argument of the `plot()` function and use the second mask argument to display the oceans (so that the ocean masks the species range).
The fill argument is specifying the displaying colour of your polygon.
We can use the function `rgb()` to specify a colour with an alpha transparency.

```{r refresh plot}
plot(assignment, who = "group",
     mask = list(mask = iucnmask, fill = rgb(1, 1, 1, 0.6)),
     mask2 = list(mask = OceanMask, fill = "navyblue", col = "navyblue"))
```


## The End

That is all for now! Here are the information of the R session we used:

```{r R session}
sessionInfo()
```

# References






