Skip to content

Commit

Permalink
added mapview vig, improved view-gradient legend
Browse files Browse the repository at this point in the history
  • Loading branch information
mtennekes committed Dec 15, 2024
1 parent 1e70fb4 commit 5fc3ce8
Show file tree
Hide file tree
Showing 9 changed files with 214 additions and 63 deletions.
37 changes: 27 additions & 10 deletions R/tmapLeafletLegend.R
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ gp_to_lpar = function(gp, mfun, shape = 20, pick_middle = TRUE, size_factor = 20
size = TRUE,
shape = TRUE)

lst = mapply(function(lsti, isnum) {
lst = mapply(function(lsti, nm, isnum) {
if (!is.character(lsti)) return(lsti)

if (nchar(lsti[1]) > 50) {
Expand All @@ -44,7 +44,19 @@ gp_to_lpar = function(gp, mfun, shape = 20, pick_middle = TRUE, size_factor = 20
i
})
if (isnum) x = lapply(x, as.numeric)
if (pick_middle) {
if (nm %in% c("fillColor", "color")) {
# create ramp of 10
not1 = which(vapply(x, length, FUN.VALUE = integer(1)) != 1L)
if (length(not1) != length(x)) {
# add NA
xNA = x[[length(x)]]
} else {
xNA = NULL
}
x[not1[-1]] = lapply(x[not1[-1]], tail, -1)
x = na.omit(unlist(x[not1]))
x = c(x[seq(1, length(x), length.out = length(not1) * 2 + 1)], xNA)
} else if (pick_middle) {
x = sapply(x, function(i) {
if (all(is.na(i))) NA else {
sq = c(5,6,4,7,3,8,2,9,1,10) # priority for middle values
Expand All @@ -57,7 +69,7 @@ gp_to_lpar = function(gp, mfun, shape = 20, pick_middle = TRUE, size_factor = 20
} else {
return(lsti)
}
}, lst, lst_isnum[names(lst)], SIMPLIFY = FALSE)
}, lst, names(lst), lst_isnum[names(lst)], SIMPLIFY = FALSE)

pch2shp = c("rect", "circle", "triangle", "plus", "cross", "diamond", "triangle",
"cross", "star", "diamond", "circle", "polygon", "plus", "cross",
Expand Down Expand Up @@ -91,7 +103,7 @@ tmapLeaflet_legend = function(cmp, lf, o, orientation) {


lab = cmp$labels
val = cmp$dvalues
val = c(cmp$dvalues)
title = if (nonempty_text(cmp$title)) expr_to_char(cmp$title) else NULL

if (!is.null(title) && !is.null(cmp$title.color)) {
Expand All @@ -116,6 +128,9 @@ tmapLeaflet_legend = function(cmp, lf, o, orientation) {
#message("Text based legends not supported in view mode")
lf
} else if (cmp$type == "gradient") {
nbins = length(val)
val = c(val, cmp$limits)

vary = if ("fill" %in% cmp$varying) "fillColor" else "color"
#vary_alpha = paste0(vary, "_alpha")

Expand All @@ -124,6 +139,7 @@ tmapLeaflet_legend = function(cmp, lf, o, orientation) {
pal = head(cmp$gp2[[vary]], -1)
colNA = tail(cmp$gp2[[vary]], 1)
textNA = lab[length(lab)]
val = c(val, NA)
} else {
pal = cmp$gp2[[vary]]
colNA = NA
Expand All @@ -150,13 +166,14 @@ tmapLeaflet_legend = function(cmp, lf, o, orientation) {
width = {if (orientation == "vertical") 20 else 200},
pal=pal,
values=val,
numberFormat = function(x) {
prettyNum(trns(x), format = "f", big.mark = ",", digits =
3, scientific = FALSE)
},
#na.label = textNA,
# numberFormat = function(x) {
# prettyNum(trns(x), format = "f", big.mark = ",", digits =
# 3, scientific = FALSE)
# },
bins = nbins,
naLabel = textNA,
title=title,
fillOpacity=cmp$gp3$alpha,
fillOpacity=cmp$gp2$fillOpacity,
layerId = layerId,
className = leg_className)

Expand Down
7 changes: 5 additions & 2 deletions README.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ editor_options:
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
out.width = "100%",
dpi = 300,
fig.width = 7.2916667,
comment = "#>",
fig.path = "man/figures/README-"
)
Expand Down Expand Up @@ -85,15 +88,15 @@ library(tmap)
Plot a World map of the happy planet index (HPI) per country.
The object `World` is an example spatial data (`sf`) object that is contained in **tmap**:

```{r fig.height=3, fig.width=8}
```{r fig.height=3.5}
tm_shape(World) +
tm_polygons(fill = "HPI")
```

This map can be enhanced in several ways.
For instance:

```{r}
```{r fig.height=4.5}
tm_shape(World, crs = "+proj=robin") +
tm_polygons(fill = "HPI",
fill.scale = tm_scale_continuous(values = "matplotlib.rd_yl_bu"),
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ tm_shape(World) +
tm_polygons(fill = "HPI")
```

![](man/figures/README-unnamed-chunk-3-1.png)<!-- -->
<img src="man/figures/README-unnamed-chunk-3-1.png" width="100%" />

This map can be enhanced in several ways. For instance:

Expand All @@ -80,7 +80,7 @@ tm_shape(World, crs = "+proj=robin") +
)
```

![](man/figures/README-unnamed-chunk-4-1.png)<!-- -->
<img src="man/figures/README-unnamed-chunk-4-1.png" width="100%" />

# Book chapter about tmap

Expand Down
Binary file modified man/figures/README-unnamed-chunk-3-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified man/figures/README-unnamed-chunk-4-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion vignettes/02_basics_scales.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ s + tm_polygons(
style = "fisher", # a method to specify the classes
n = 7, # number of classes
midpoint = 38, # data value mapped to the middle palette color
values = "pu_gn_div" # color palette; run cols4all::c4a_gui() to explore color palettes
values = "pu_gn_div" # color palette;
# run cols4all::c4a_gui() to explore color palettes
))
```

Expand Down
29 changes: 15 additions & 14 deletions vignettes/31_versus_ggplot2.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -91,20 +91,21 @@ We can use `tmap` to match the style of `ggplot2`:

```{r}
tm_shape(World, crs = "+proj=eqearth") +
tm_polygons(fill = "HPI",
col = "grey20",
lwd = 1,
fill.scale = tm_scale_continuous(values = "pu_gn", midpoint = 35),
fill.legend = tm_legend(reverse = TRUE,
frame = FALSE,
item.height = 2.25,
item.width = 1.8,
position = tm_pos_out(pos.v = "center"),
na.show = FALSE,
ticks = list(c(0, 0.1), c(0.9, 1)),
ticks.col = "white",
col = "white")) +
tm_layout(frame = FALSE, outer.margins = 0)
tm_polygons(
fill = "HPI",
col = "grey20",
lwd = 1,
fill.scale = tm_scale_continuous(values = "pu_gn", midpoint = 35),
fill.legend = tm_legend(reverse = TRUE,
frame = FALSE,
item.height = 2.25,
item.width = 1.8,
position = tm_pos_out(pos.v = "center"),
na.show = FALSE,
ticks = list(c(0, 0.1), c(0.9, 1)),
ticks.col = "white",
col = "white")) +
tm_layout(frame = FALSE, outer.margins = 0)
```


132 changes: 132 additions & 0 deletions vignettes/32_versus_mapview.Rmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
---
title: "tmap versus: mapview"
output:
bookdown::html_vignette2:
pkgdown:
as_is: true
template:
math-rendering: mathjax
bibliography: '`r system.file("tmap.bib", package="tmap")`'
csl: "`r system.file('ieee.csl', package = 'tmap')`"
editor_options:
chunk_output_type: console
---

```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
out.width = "100%",
dpi = 300,
fig.width = 7.2916667,
comment = "#>"
)
hook_output <- knitr::knit_hooks$get("output")
knitr::knit_hooks$set(output = function(x, options) {
lines <- options$output.lines
if (is.null(lines)) {
return(hook_output(x, options)) # pass to default hook
}
x <- unlist(strsplit(x, "\n"))
more <- "..."
if (length(lines)==1) { # first n lines
if (length(x) > lines) {
# truncate the output, but add ....
x <- c(head(x, lines), more)
}
} else {
x <- c(more, x[lines], more)
}
# paste these lines together
x <- paste(c(x, ""), collapse = "\n")
hook_output(x, options)
})
```


```{r, echo = FALSE, message = FALSE}
library(tmap)
tmap_options(scale = 1)
```

## Mapview

Mapview is an excellent R package for interactive maps. When to use which package? This is what ChatGPT answered:

| Use Case | Recommended Package |
|-------------------------------------------|----------------------|
| High-quality thematic maps for publication | `tmap` |
| Quick exploratory visualization of spatial data | `mapview` |
| Need both static and interactive maps | `tmap` |
| Debugging or inspecting spatial datasets | `mapview` |
| Comparing multiple variables or time steps | `tmap` (facets) |
| Large datasets for interactive exploration | `mapview` |

Pretty accurate I would say. In addition:
* tmap has a more sophisticated/complex syntax that is based on the [grammar of graphics](21_theory_gg) and is therefore popular for education purposes
* mapview is a front runner in terms of interactive features and is probably a bit faster.

Worth noting is that the development teams of tmap and mapview collaborate a lot, which also holds for R-spatial developers in general.

## Modes / platforms

* tmap offers two modes: "plot" and "view" (but is extendable, see https://github.com/r-tmap/tmap.deckgl).
* mapview supports three modes, which they call *platforms*: "leaflet", "leafgl", and "mapdeck".

tmap "view" (with `tm_view(use_WebGL = FALSE)`) is similar to mapview "leaflet"
tmap "view" (with `tm_view(use_WebGL = TRUE)`) is similar to mapview "leafgl"

tmap does not offer a mode using Mapbox yet


## Default maps

This is the default output of `mapview`:

```{r fig.height = 3.5}
library(mapview)
mapview(World)
```


This is the default output of `tmap`:

```{r fig.height = 3.5}
tmap_mode("view")
qtm(World) # qmt stands for 'quick thematic map'
```

## Choropleth


```{r fig.height = 3.5}
mapview(World, z = "HPI")
```

```{r fig.height = 3.5}
tm_shape(World) +
tm_polygons(fill = "HPI")
```


## Mimicking mapview layout

We can use `tmap` to match the style of `mapview`:

```{r fig.height = 3.5}
tm_shape(World) +
tm_polygons(
fill = "HPI",
fill_alpha = 0.6,
col_alpha = 0.9,
fill.legend = tm_legend(
title = "World - HPI",
position = c("right", "top"),
fill_alpha = 1),
fill.scale = tm_scale_continuous(values = "viridis", n = 7, value.na = "#BEBEBE")
) +
tm_basemap(c("CartoDB.Positron", "CartoDB.DarkMatter",
"OpenStreetMap", "Esri.WorldImagery", "OpenTopoMap"))
```


Loading

0 comments on commit 5fc3ce8

Please sign in to comment.