rplotcolorbarr-mapview

Point color and symbol size based on different variables in mapview


I'm trying for a divergent scale theme in mapview to help visualize gains vs. losses, with:

any ideas?


library(tidyverse)
library(mapview)
library(sf)

lat <- rep(34,16)
lon <- seq(-128, -126, length = 16)
value <- c(-1000, -800, -600, -400, -200, -100, -50, 
            -25, 25, 50, 100, 200, 400, 600, 800, 1000)

#make data.frame
df <- data.frame(lat, lon, value) 

#make spatial object for mapview
df <- st_as_sf(df, coords = c("lon", "lat"), crs = 4326) %>%
      mutate(value_abs = abs(value)) #value_abs intended for `cex` argument

pal <-  mapviewPalette("mapviewSpectralColors") #from mapview doc. example
m   <-  mapview(df["value"], #sets hover over value as this column
         cex = "value",      #sets circle diameter scaling on this column
         legend = TRUE,
         col.regions = pal(100), #closest I found to a red-blue divergent scale
         layer.name = "value")  
m

In other words, I'm hoping for the pattern of points here below to be symmetrical with the left side as a mirror image of the right in size, but with blue circles at left, red at right, and still allowing the user to see the actual (non absolute) values (e.g. -1000) by mouseover.

enter image description here

attempts: switching cex = "value" with cex = "value_abs" yields warning: In min(x) : no non-missing arguments to min; returning Inf without any points drawn, or with cex = df$value_abs (no quotes), which makes uncolored, enormous points. I'm not planning on needing two legends - just one for either the circle size or fill, showing a min and max value like it does now, would be great.


Solution

  • You are very close. You need to explicitly refer to df$value_abs. Look below:

    library(tidyverse)
    library(mapview)
    library(sf)
    
    df <- data.frame(lat=rep(34,16), 
                     lon=seq(-128, -126, length = 16), 
                     value=c(-1000, -800, -600, -400, -200, -100, -50, 
                             -25, 25, 50, 100, 200, 400, 600, 800, 1000)) 
    
    df <- st_as_sf(df, coords = c("lon", "lat"), crs = 4326) %>%
                   mutate(value_abs = abs(value))
    
    pal <-  mapviewPalette("mapviewSpectralColors")
    mapviewOptions(fgb = FALSE) ## see https://stackoverflow.com/a/65614281
    
    mapview(df["value"], 
                    cex = df$value_abs/100, 
                    legend = TRUE,
                    col.regions = pal(100), 
                    layer.name = "value")  
    
    

    Created on 2019-06-24 by the reprex package (v0.3.0)