Last updated: 2025-01-03

Checks: 7 0

Knit directory: R_tutorial/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20241223) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 9fccd1e. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/

Unstaged changes:
    Modified:   analysis/index.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/Interactive_Maps.Rmd) and HTML (docs/Interactive_Maps.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 9fccd1e Ohm-Np 2025-01-03 wflow_publish("analysis/Interactive_Maps.Rmd")
html 24f878a Ohm-Np 2025-01-03 Build site.
Rmd 20c6879 Ohm-Np 2025-01-03 wflow_publish("analysis/Interactive_Maps.Rmd")

Up to this point, we have created several plots for vector data, raster data, and data frames. However, R also supports interactive visualizations through powerful packages such as plotly, tmap, leaflet, mapview, among others. These tools enable the creation of dynamic and engaging visual representations of data.

In this chapter, we will explore various methods for creating visualizations in R, helping you communicate insights more effectively. To begin, we will install all the packages required for creating interactive maps in this chapter.

# set CRAN mirror
options(repos = c(CRAN = "https://cran.rstudio.com/"))

# packages are only installed when necessary, avoiding repeated output
packages <- c("plotly", "leaflet", "mapview")
installed_packages <- rownames(installed.packages())
missing_packages <- packages[!(packages %in% installed_packages)]
if(length(missing_packages)) install.packages(missing_packages, quiet = TRUE)

Plotly

Creating interactive maps with plotly in R is a great way to visualize geospatial data dynamically. Below is an example of how you can create interactive maps using plotly with vector data and raster data.

Interactive Maps with Vector Data

The plotly library can visualize vector data (e.g., polygons or points) by converting it into a sf object and plotting it using plot_ly.

# Load required libraries
library(sf)
library(dplyr)
library(plotly)

# Load vector data
gadm_data <- read_sf("data/vector/kanchanpur.gpkg")

# Create an interactive map
fig <- plot_ly() %>%
  add_sf(data = gadm_data,
         type = "scatter",
         color = ~NAME,
         text = ~NAME,
         hoverinfo = "text") %>%
  layout(
    annotations = list(
      text = "Interactive Map of Kanchanpur District",
      x = 0.5,                                       # Center align
      y = -0.1,                                      # Position below the plot
      showarrow = FALSE,                             # No arrow
      xref = "paper",                                # Relative to the chart
      yref = "paper",                                # Relative to the chart
      font = list(size = 16)                         # Font size
    )
  )

fig
  • color: Use a column in your dataset to differentiate areas.
  • hoverinfo: Displays additional information when you hover over the map.

This interactive plot provides several features to explore the data dynamically. You can hover over elements on the map to view detailed information displayed as tooltips. Use the legend to toggle the visibility of specific categories or data groups. Zoom in and out using the scroll wheel on your mouse or the touchpad, and pan across the map by clicking and dragging. Additionally, double-clicking on the plot resets it to its original view. These tools make it easy to explore and analyze the data visually.

Interactive Maps with Raster Data

To visualize raster data interactively, you can convert it into a data frame with terra and then use plot_ly to plot it.

library(terra)

# Load raster data
r <- rast("data/raster/landcover_2019.tif")

# Convert raster to data frame
r_df <- as.data.frame(r, xy = TRUE)
colnames(r_df)
[1] "x"                                                                                
[2] "y"                                                                                
[3] "E080N40_PROBAV_LC100_global_v3.0.1_2019-nrt_Discrete-Classification-map_EPSG-4326"
# Rename the 3rd column
colnames(r_df)[3] <- "layer"

# Create an interactive heatmap
fig <- plot_ly(
  data = r_df,
  x = ~x,
  y = ~y,
  z = ~layer,
  type = "heatmap",
  colors = "viridis",
  hoverinfo = "x+y+z"
) %>%
  layout(title = "ESA Land Cover (2019)")

fig
  • type = “heatmap”: Creates a heatmap from raster data.
  • z: The raster value for each cell.
  • hoverinfo: Displays cell coordinates and values on hover.

Interactive Maps with Combined Data

You can combine vector and raster data in a single interactive map. Combine the vector gadm_data and raster r_df from previous sections.

# Create an interactive map with raster and vector layers
fig <- plot_ly() %>%
  add_trace(
    data = r_df,
    x = ~x,
    y = ~y,
    z = ~layer,
    type = "heatmap",
    colors = "viridis",
    showscale = TRUE,
    hoverinfo = "x+y+z"
  ) %>%
  add_sf(
    data = gadm_data,
    type = "scatter",
    color = I("yellow"),
    opacity = 0.5,
    text = ~NAME,
    hoverinfo = "text"
  ) %>%
  layout(title = "Combined Interactive Map")

fig
  • add_trace(): Adds raster data as a heatmap.
  • add_sf(): Overlays vector data (e.g., boundaries).
  • layout(): Adjusts the overall layout of the map.

Advantages of Plotly for Maps:

  • User-friendly interactivity.
  • Easy to integrate with other plotly visualizations.
  • Highly customizable with tooltips, legends, and layout options.

Leaflet

Interactive maps with the leaflet package in R provide an excellent way to create dynamic and interactive geospatial visualizations. The leaflet package is user-friendly and supports features like zooming, panning, popups, and markers.

Basic Interactive Map

Here’s how to create a simple interactive map:

library(leaflet)
leaflet() %>%
  addTiles() %>% # Add default openStreetMap tiles
  addMarkers(
    lng = 80.3547, lat = 28.6895,
    popup = "Belauri Municipality, Nepal"
  )
  • addTiles(): Adds the default OpenStreetMap base layer.
  • addMarkers(): Places a marker at the specified longitude (lng) and latitude (lat).
  • popup: Text displayed when clicking the marker.

Mapping Vector Data

You can map vector data, such as polygons or points, from an sf object.

library(sf)

# Load vector data
gadm_data <- read_sf("data/vector/kanchanpur.gpkg")

# Create a leaflet map
leaflet(data = gadm_data) %>%
  addTiles() %>%  # Add basemap
  addPolygons(
    color = "blue", 
    weight = 2, 
    opacity = 0.7,
    popup = ~NAME
  )
  • addPolygons(): Plots polygon data.
  • color, weight, and opacity: Control the appearance of the polygons.
  • popup: Displays a specific column (NAME) as a popup.

Mapping Raster Data

Raster data can also be visualized using the leaflet package.

library(terra)

# Load raster data
raster_data <- rast("data/raster/landcover_2019.tif")

# Convert raster to a leaflet-compatible format
raster_leaflet <- projectRasterForLeaflet(raster_data, method = "bilinear")

# Create a leaflet map with raster
leaflet() %>%
  addTiles() %>%  # Add basemap
  addRasterImage(
    raster_leaflet, 
    colors = colorNumeric("viridis", values(raster_leaflet), na.color = "transparent"),
    opacity = 0.8
  ) %>%
  addLegend(
    pal = colorNumeric("viridis", values(raster_leaflet), na.color = "transparent"),
    values = values(raster_leaflet),
    title = "ESA Land Cover"
  )
  • addRasterImage(): Adds the raster layer.
  • colorNumeric(): Defines the color scale.
  • addLegend(): Adds a legend for the raster data.

Customizing Leaflet Maps

You can add multiple layers and allow users to switch between them using addLayersControl() and also add circle markers using addCircleMarkers(). You can create popups that display information from your dataset dynamically.

leaflet() %>%
  addTiles(group = "OSM Default") %>%
  addProviderTiles("CartoDB.Positron", group = "Carto Light") %>%
  addPolygons(data = gadm_data,
              color = "blue",
              group = "NAME",
              popup = ~paste("VDC:", NAME)) %>%
  addLayersControl(
    baseGroups = c("OSM Default", "Carto Light"),
    overlayGroups = c("Regions"),
    options = layersControlOptions(collapsed = FALSE)
  ) %>%
  addCircleMarkers(
    lng = 80.3547, lat = 28.6895, 
    radius = 8, color = "red", 
    popup = "Belauri Municipality, Nepal"
  )

Advantages of Leaflet:

  • Highly interactive and user-friendly.
  • Extensive customization options (basemaps, markers, popups, etc.).
  • Lightweight and suitable for web integration.

Mapview

Creating interactive maps with mapview in R is a simple and effective way to visualize geospatial data interactively. The mapview package is designed to provide quick, easy, and interactive maps using leaflet internally, with minimal code. It works well with sf, and SpatRaster objects.

Here’s how to use mapview to create interactive maps for various types of geospatial data:

Basic Interactive Map

You can create a basic interactive map by simply calling mapview() on your geospatial object.

library(sf)
library(mapview)

# Create a data frame with point data
point_data <- data.frame(
  lat = c(28.6895),
  lon = c(80.3547),
  popup = c("Belauri Municipality")
)

# Convert to an sf object
point_sf <- st_as_sf(point_data, coords = c("lon", "lat"), crs = 4326)

# Plot the point using mapview
mapview(point_sf)
  • st_as_sf(): Converts the data frame to an sf object, which is compatible with mapview.
  • mapview(): Plots the sf object interactively.

Plotting Vector Data

You can plot vector data like polygons using mapview as well.

# Load vector data
gadm_data <- read_sf("data/vector/kanchanpur.gpkg")

# Plot the polygon using mapview
mapview(gadm_data)
  • mapview() will display the polygons interactively.
  • You can adjust the colors, labels, and other aspects of the polygons with additional parameters (e.g., color, popup, etc.).

Plotting Raster Data

mapview can also handle raster data. For instance, when you have a raster dataset representing Population Count, it can be plotted interactively.

# Load vector data
raster_data <- rast("data/raster/reclassified.tif")

# Plot the polygon using mapview
mapview(raster_data)
  • mapview() automatically handles the rendering of raster layers and creates an interactive map.

Combining Multiple Layers

You can combine vector and raster data layers in a single map view.

# Create an interactive map with both vector and raster data
mapview(gadm_data) + mapview(raster_data)

Advantages of mapview:

  • Quick and Easy
  • Customizable
  • Works with Multiple Data Types
  • Built-in Integration

For this tutorial, this concludes the coverage of Interactive Visualizations in R. If you would like to explore additional packages for interactive maps, examples, or need clarification on any of the steps covered, please visit the GitHub repository: R_tutorial and feel free to open an issue.


sessionInfo()
R version 4.4.0 (2024-04-24 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 11 x64 (build 22631)

Matrix products: default


locale:
[1] LC_COLLATE=English_Germany.utf8  LC_CTYPE=English_Germany.utf8   
[3] LC_MONETARY=English_Germany.utf8 LC_NUMERIC=C                    
[5] LC_TIME=English_Germany.utf8    

time zone: Europe/Berlin
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] mapview_2.11.2  leaflet_2.2.2   terra_1.8-5     plotly_4.10.4  
[5] ggplot2_3.5.1   dplyr_1.1.4     sf_1.0-19       workflowr_1.7.1

loaded via a namespace (and not attached):
 [1] tidyselect_1.2.1        viridisLite_0.4.2       farver_2.1.2           
 [4] fastmap_1.2.0           lazyeval_0.2.2          promises_1.3.0         
 [7] digest_0.6.36           lifecycle_1.0.4         processx_3.8.4         
[10] magrittr_2.0.3          compiler_4.4.0          rlang_1.1.4            
[13] sass_0.4.9              tools_4.4.0             leafpop_0.1.0          
[16] utf8_1.2.4              yaml_2.3.10             data.table_1.15.4      
[19] knitr_1.48              brew_1.0-10             htmlwidgets_1.6.4      
[22] sp_2.1-4                classInt_0.4-10         RColorBrewer_1.1-3     
[25] abind_1.4-5             KernSmooth_2.23-22      withr_3.0.2            
[28] purrr_1.0.2             grid_4.4.0              stats4_4.4.0           
[31] fansi_1.0.6             git2r_0.33.0            e1071_1.7-16           
[34] leafem_0.2.3            colorspace_2.1-1        scales_1.3.0           
[37] cli_3.6.3               rmarkdown_2.28          generics_0.1.3         
[40] rstudioapi_0.16.0       httr_1.4.7              DBI_1.2.3              
[43] cachem_1.1.0            proxy_0.4-27            stringr_1.5.1          
[46] stars_0.6-6             parallel_4.4.0          s2_1.1.7               
[49] base64enc_0.1-3         vctrs_0.6.5             jsonlite_1.8.8         
[52] callr_3.7.6             systemfonts_1.1.0       crosstalk_1.2.1        
[55] tidyr_1.3.1             jquerylib_0.1.4         units_0.8-5            
[58] lwgeom_0.2-14           glue_1.7.0              codetools_0.2-20       
[61] ps_1.8.1                leaflet.providers_2.0.0 stringi_1.8.4          
[64] gtable_0.3.5            later_1.3.2             raster_3.6-26          
[67] munsell_0.5.1           tibble_3.2.1            pillar_1.9.0           
[70] htmltools_0.5.8.1       satellite_1.0.5         R6_2.5.1               
[73] wk_0.9.4                rprojroot_2.0.4         evaluate_0.24.0        
[76] lattice_0.22-6          png_0.1-8               httpuv_1.6.15          
[79] bslib_0.8.0             class_7.3-22            Rcpp_1.0.13            
[82] uuid_1.2-1              svglite_2.1.3           whisker_0.4.1          
[85] xfun_0.47               fs_1.6.4                getPass_0.2-4          
[88] pkgconfig_2.0.3