简体   繁体   中英

duplicated colors in legend of tmap object in R

has anyone encountered such problems with tmap in R ? See the plot below. No matter which style I tried ( pretty , kmeans , jenks to name a few), there were always duplicated colors in the legend. I also tried setting midpoint = NA , but the problem persisted.

Here is the code I used to create such a plot. Below the code is the vector for plotting. Sorry that dput seems not working with sf objects. Please feel free to use any spatial data to replicate the example. Feedback is always appriciated!

tm_shape(sfpr) + tm_borders(col = "gray") + 
  tm_polygons(col = 'Pperc', 
              style = "kmeans",
#              midpoint = NA,
              palette = viridis(4, begin = 0.48, end = 1)) + 
  tm_layout(inner.margins = c(0.1, 0.15, 0.1, 0.1), 
            legend.title.size = 1.5, 
            legend.text.size = 1.1, 
            legend.position = c("left", "bottom"), 
            legend.format = list(digits = 0), 
            main.title = "Maps on the reduction of phosphate losses (in 1000 lbs)", 
            main.title.position = "center")
> sfpr$Pperc
 [1]   -1.49   -0.02    0.12    0.27   -0.36 -247.86  -21.74   -8.88   28.63  -14.48   -0.56

在此处输入图片说明

The issue is caused by negative and positive values in your dataset. If you set auto.palette.mapping = T (deprecated) or play around with different numeric values for midpoint this will solve your problem. I generated some dummy data based on your min/max values. Btw, you should either use tm_borders() + tm_fill() or only tm_polygons() since the latter one fills the polygons as well as draws the outline.

library(tidyverse)
library(tmap)
library(sf)
library(urbnmapr)
library(viridis)

# create dummy data
sfpr <- get_urbn_map("states", sf = T) %>%  
  as.tibble() %>% 
  mutate(Pperc = runif(51, -248 ,29)) %>% 
  st_as_sf() 

tm_shape(sfpr) +
  tm_borders(col = "gray") + 
  tm_fill("Pperc",
          style = "kmeans",
          palette = viridis(4, begin = 0.48, end = 1), 
          auto.palette.mapping = T) +
  tm_layout(inner.margins = c(0.1, 0.15, 0.1, 0.1), 
            legend.title.size = 1.5, 
            legend.text.size = 1.1, 
            legend.position = c("left", "bottom"), 
            legend.format = list(digits = 0), 
            main.title = "Maps on the reduction of phosphate losses (in 1000 lbs)", 
            main.title.position = "center")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM