class: center, top ![:scale 30%](/assets/images/coding_club_logo_1.png) # 28 NOVEMBER 2024 ## INBO coding club Herman Teirlinck
01.23 - Léon Stynen --- class: left, top ## ROOMIE: room reservation ``` > if (isFALSE(roomie)) { + warning("Please confirm asap the room reservation on the roomie.") + } Warning message: Please confirm asap the room reservation on the roomie. ``` ## Start recording ``` > if (isFALSE(recordIsON)) { + warning("Please start recording asap!") + } Warning message: Please start recording asap! ``` --- class: center, middle ![:scale 90%](/assets/images/20241128/20241128_badge.png) --- class: left, top What do we mean with geospatial data? ### Spatial vector data Points, lines, polygons, etc were the topic of the coding club of [28 May 2024](https://inbo.github.io/coding-club/sessions/20240528_spatial_data_in_r_with_sf.html#1). - **sf** : newest and recommended package - **sp** : its predecessor (retired) ### Spatial raster data Rasters were the topic of the coding club of [24 November 2022](https://inbo.github.io/coding-club/sessions/20221124_coding_club_rasters.html). - [**terra**](https://rspatial.github.io/terra/reference/terra-package.html) : newest and recommended package - [**raster**](https://rspatial.org/raster/pkg/index.html) : its predecessor (no support for sf), match with sp - [**stars**](https://r-spatial.github.io/stars/): for **s**patio**t**emporal **ar**ray**s**. Important for people involved in remote sensing where data often comes in the form of dense arrays, with space and time being array dimensions. For more info, read this great [article](https://geocompx.org/post/2021/spatial-classes-conversion/) about conversions among different spatial classes in R. --- class: left, top # Today Today we play around the visualization of **spatial vector data** only. No raster data! --- class: left, top # Plot vs maps You can **plot** geospatial data. But a plot is not a map, as chocolate is not (yet) a chocolate pie. You need one "ingredient" more. What do we need? ![:scale 90%](/assets/images/20241128/20241128_plot.png) --- class: left, top # From plots to maps You need **tiles**. ![:scale 90%](/assets/images/20241128/20241128_map.png) Example above uses [OpenStreetMap](https://www.openstreetmap.org/) tiles. --- class: left, top # Tiles There are a lot of tiles. Some are available for being used with an open license, others not. Tiles are nothing more than images (pngs or jpgs). They are small images that are put together to form a map. The tiles are usually 256x256 pixels and are arranged in a grid. The tiles are generated by a server and are requested by the client (your browser) when you zoom in or out on a map. There are tiles covering the entire world, or just a specific region. For Flanders, see the [Web Map (Tile) Service](https://www.vlaanderen.be/digitaal-vlaanderen/onze-oplossingen/geografische-webdiensten/ons-gis-aanbod/raadpleegdiensten#wat-is-een-wmts) (WMTS) of the Flemish Authority. So, if you have ever seen a map on the web, you have seen tiles! And if you have ever heard a know-it-all speaking about WMTS, well, do not be afraid about that! --- class: left, top # Static vs dynamic maps **Static maps**: the data visualized on the map and the background tiles are fixed: no zooming in/out. Easy for pdfs or other static content. **dynamic maps**: zooming in/out is possible. Perfect for web pages. --- class: left, top ## Geospatial visualization in R Geospatial visualization in R is evolving fast. The packages are numerous and the choice is not always easy. The [R-Spatial CRAN Task View](https://github.com/cran-task-views/Spatial/tree/main)* is a handy source to get an updated overview of R spatial packages. See section related to [visualization](https://github.com/cran-task-views/Spatial/blob/main/Spatial.md#visualizing-spatial-data). Another tip: choose packages actively maintained!
* __Note__: the CRAN Task View is a curated list of R packages for a particular task. It is maintained by the community. And thanks Floris Vanderhaeghe for the tip!
--- class: left, top # Packages used today Today we will mainly use: - ggplot: allows to plot geospatial vector data. No maps! - [ggspatial](https://paleolimbot.github.io/ggspatial/index.html): a tidy framework for interacting with spatial data using ggplot2 as a plotting backend. - [mapview](https://r-spatial.github.io/mapview/): the package for creating interactive maps very quickly and conveniently. Fill the gap of quick (not presentation grade) interactive plotting to examine and visually investigate spatial data. It uses [Leaflet](http://leafletjs.com/) or [Mapbox GL](https://docs.mapbox.com/mapbox-gl-js/api/)+ [Deck.gl](https://deck.gl/) javascript libraries in the background via [mapdeck](https://symbolixau.github.io/mapdeck/articles/mapdeck.html). Your first choice before moving to leaflet. --- class: left, top ## Install and load packages ```r # Load the packages and install if needed required_packages <- c( "sf", "ggplot2", "ggrepel", # For avoiding label overlapping "ggspatial", "prettymapr", # For using map tiles with ggspatial "raster", # For using map tiles with ggspatial "mapview", "leafem", # For providing extensions to leaflet maps "leafpop", # For including tables, images and graphs in leaflet pop-ups "inbospatial" # For using useful R functions for dealing with spatial data ) # Install packages not yet installed installed_packages <- required_packages %in% rownames(installed.packages()) if (any(installed_packages == FALSE)) { if (!"https://inbo.r-universe.dev" %in% getOption("repos")) { # Install inbospatial via GitHub devtools::install_github("inbo/inbospatial") # Remove inbospatial from the list of packages to install required_packages <- required_packages[required_packages != "inbospatial"] } # Install packages not yet installed install.packages(required_packages[!installed_packages]) } # Load packages invisible(lapply(required_packages, library, character.only = TRUE)) ``` --- class: center, top ### How to get started? Check the [Each session setup](https://inbo.github.io/coding-club/gettingstarted.html#each-session-setup) to get started. ### First time coding club? Check the [First time setup](https://inbo.github.io/coding-club/gettingstarted.html#first-time-setup) section to setup. --- class: left, top ![:scale 100%](/assets/images/coding_club_sticky_concept.png)
No yellow sticky notes online. We use hackmd (see next slide) but basic principle doesn't change. --- class: center, top ### Share your code during the coding session! Go to https://hackmd.io/xnVuPm-KS_-3oEIMHSrdJQ?edit
--- class: left, top # Download data and code - Download everything automatically via `inborutils::setup_codingclub_session()` - manually*, from [data/20241128](https://github.com/inbo/coding-club/blob/master/data/20241128/) and [src/20241128](https://github.com/inbo/coding-club/blob/master/src/20241128). Place the R script in your folder `src/20241128/` and data in `data/20241128/`.
* __Note__: check the getting started instructions on [how to download a single file](https://inbo.github.io/coding-club/gettingstarted.html#each-session-setup)
--- class: left, top # Data and code files description 1. [20241128_ias_union_concern_Natura2000_B.gpkg](https://github.com/inbo/coding-club/blob/master/data/20241128_ias_union_concern_Natura2000_B.gpkg)*: geopackage with the number of alien species of Union concern observed in the Flemish NATURA2000 protected areas, type B. 2. [20241128_flemish_municipalities.gpkg](https://github.com/inbo/coding-club/blob/main/data/20241128/20241128_flemish_municipalities.gpkg): geopcakge with the Flemish municipalities. 3. [20241128_challenges.R](https://github.com/inbo/coding-club/blob/master/src/20241128/20241128_challenges.R): R script to start from. \* Derived from a geopackage with all European Natura2000 areas: https://www.eea.europa.eu/en/datahub/datahubitem-view/6fc8ad2d-195d-40f4-bdec-576e7d1268e4 --- background-image: url(/assets/images/background_challenge_1.png) class: left, top # Challenge 1 - plots **IMPORTANT**: The code to read the spatial files is provided! 1. How to plot the Natura2000 areas with ggplot? **Fill** the areas based on the number of alien species of Union concern, `n_ias`. This kind of map is known as **choropleth map**. Hint: see documentation of the [geom_sf](https://ggplot2.tidyverse.org/reference/ggsf.html) function or the general hint below. 2. Add the site code (`SITECODE` column) as labels. Show them in black, with fontsize 2 and bold style. 3. A pure ggplot question: how to set the color of the borders of the Natura2000 areas to black? 4. A pure ggplot question: **Scale** the color using the **c**ontinuous **viridis** palette. Hint: see documentation of the [scale_fill_viridis](https://ggplot2.tidyverse.org/reference/scale_viridis.html) family of functions. 5. How to avoid overlapping labels? Hint: see the general hint below. **General hint**: Follow the first part of this good [tutorial](https://r-charts.com/spatial/maps-ggplot2/) from R CHARTS! --- background-image: url(/assets/images/background_challenge_2.png) class: left, top # Challenge 2 - static maps Let'use [ggspatial](https://github.com/paleolimbot/ggspatial) to create static maps. 1. Let's add now map tiles from OpenStreetMap (default) as background. Is the resolution of the automaticaly chosen zoom level not enough? Increase it, but still do not hardcode the zoom level. Hint: Type `?annotation_map_tile` in the R console to get help. 2. Add caching option to avoid downloading the tiles each time you run the code. 3. Add a north arrow at the top right corner of the map and a scale bar at the bottom left corner. Hint: see [dedicated section](https://paleolimbot.github.io/ggspatial/articles/ggspatial.html#using-north-arrow-and-scalebar) in ggspatial article. 4. Which other tiles you can use with `annotation_map_tile()`? Test them and let's find your favourite ones. --- class: left, top ## Intermezzo: leaflet vs mapview [Leaflet](https://leafletjs.com/) is a very popular JavaScript library for interactive maps by [Vladamir Agafonkin](http://agafonkin.com/en/). The R package [leaflet](https://rstudio.github.io/leaflet/) is a wrapper for that library. It allows to create interactive maps that can be embedded in a web page. The package is very flexible and allows to create maps with a lot of functionalities. The documentation is wonderful and there are a lot of examples available (check the "Articles"!). However, if you are looking for a quick and easy way to create interactive maps, you can use [mapview](https://r-spatial.github.io/mapview/). It allows to create interactive maps with just one line of code (= less verbose). It is very useful to quickly explore your data and to create maps for presentations or reports. The documentation is also very good and there are a lot of examples available in the "Articles". --- background-image: url(/assets/images/background_challenge_3.png) class: left, top # Challenge 3 - dynamic maps: vector data Using [mapview](https://r-spatial.github.io/mapview/): 1. Show number of alien species of Union concern for Natura2000 areas on a map. The color of the areas should represent the number of alien species. Display the legend. Set the contour of the areas in gray30. What happens when clicking on an area? Beautiful, isn't? 2. Let's fine tune the previous map. Use "OpenStreetMap" map tiles only, set the opacity of the areas to 0.8 and the contour lines to 0.1. Set `"Alien species of Union concern"` as legend title and layer name. Show only `SITECODE`, `NAAM` and `n_ias` in the popups. Hint: [mapview advanced controls](https://r-spatial.github.io/mapview/articles/mapview_02-advanced.html) and [mapview popups](https://r-spatial.github.io/mapview/articles/mapview_04-popups.html). 3. Create a separate map with the municipalities of Belgium. Use black as line color. Set layer name as `"municipality"`. Again, allow Open Street Map tiles only. No legend. Set line width of the polygons to 1 and set opacity of the polygons to 0. 4. Combine the two maps. Make sure the hover text still shows the number of alien species. 5. You have already installed and loaded [leafem](https://r-spatial.github.io/leafem/), a package with leaflet extensions for mapview, so you should see by default the mouse coordinates (lat, lon) and zoom level on top left. If not, check how to add them in the [extra leaflet functionalities](https://r-spatial.github.io/mapview/articles/mapview_06-add.html) vignette. --- class: left, top ## Intermezzo: INBO goes spatial Do you know INBO is very active in spatial data? Just think about qgisprocess package (see coding club of Dec 2023).But check also the R package [inbospatial](https://github.com/inbo/inbospatial): a collection of useful R functions for spatial data. Version 0.0.3 has been released just few days ago. ![:scale 90%](/assets/images/20241128/20241128_inbospatial_0_0_3.png) --- class: left, top # Bonus challenge - inbospatial Amog other things, inbospatial provides a lot of layers! 1. Add to the previous dynamic map, for example, the layer related to the public forest and nature areas managed by the [Flemish Nature & Forest Agency](https://www.natuurenbos.be/). 2. Use the GRB basemap (Grootschalig Referentiebestand) as map tiles to have very good detailed borders of municipalities. Use this layer instead of the municipality layer. Hint: check the documentation ["adding WMS tiles"](https://inbo.github.io/inbospatial/reference/add_wms.html). NOTE: while trying adding these layers it could be that you get an error saying you need to install some extra leaflet packages: `leaflet.extras` and `leaflet.extras2`. Install them and try again. --- class: left, top ## Leaflet extra exercises Leaflet or not to leaflet? It's up to you! You can stick to work with mapview or you can go full throttle with leaflet. Check the bonus challenges of the INBO coding club of August 31, 2023 for more inspiration. The [leaflet for R](https://rstudio.github.io/leaflet/) documentation is one of the best package documentations ever written, that's for sure! --- class: left, top # The packages of the month - Amber's choice Do you dream of switching from static to dynamic maps with one line of code? Well, give [tmap](https://r-tmap.github.io/tmap/) a try! Give a look to the [Get Started](https://r-tmap.github.io/tmap/articles/tmap-getstarted.html) page: ``` tmap_mode("view") # to dynamic maps tmap_mode("plot") # to static maps ``` Less flexible than mapview but the possibility to switch from static to dynamic visualization is really a nice-to-have. ![:scale 90%](/assets/images/20241128/20241128_tmap.png) --- class: left, top # The packages of the month - Damiano's choice Ever heard about the Geographic Information System of the Commission, [GISCO](https://ec.europa.eu/eurostat/web/gisco)? And about [giscoR](https://ropengov.github.io/giscoR/)? giscoR is a package that allows you to download spatial data from the GISCO portal. It is a great tool to get administrative boundaries, land cover, etc. for the entire Europe/world. The package is still in development but it is already very useful. Check the [vignette](https://cran.r-project.org/web/packages/giscoR/vignettes/giscoR.html) to get started. ![:scale 110%](/assets/images/20241128/20241128_giscoR.png) --- class: left, top # Resources - Challenges solutions and edited video recording will be available soon. - [ggplot2](https://ggplot2.tidyverse.org/): our standard package for plots, which can also be used for displaying spatial data. - [ggspatial](https://paleolimbot.github.io/ggspatial/index.html) documentation. Suit well for static maps and ggplot2 compatible. - Are you a ggplot fan? The package [ggmap](https://github.com/dkahle/ggmap#readme) is also something you will enjoy! - [mapview](https://r-spatial.github.io/mapview/) documentation. - [leaflet](https://rstudio.github.io/leaflet/) for R documentation. - [leafem](https://r-spatial.github.io/leafem/) documentation. - [leafpop](https://rdrr.io/cran/leafpop/) documentation. - [inbospatial](https://github.com/inbo/inbospatial): a collection of useful R functions for spatial data made in INBO. - [tmap](https://r-tmap.github.io/tmap/) documentation. - [giscoR](https://ropengov.github.io/giscoR/) documentation. --- class: center, middle ![:scale 30%](/assets/images/coding_club_logo_1.png) Topic: RepoRts
Room: HT - 01.69 - Paul Janssen
Date: **17/12/2024**, van **10:00** tot **12:00**
Help needed with packages or setup? You are welcom from **9:45**