R语言 基于结果的自定义Tmap调色板

bq9c1y66  于 2023-02-17  发布在  其他
关注(0)|答案(2)|浏览(150)

问题已解决,感谢asnwers

1szpjjfi

1szpjjfi1#

你需要创建一个调色板--一个命名的矢量,它将参与者的名字链接到颜色上。https://r-tmap.github.io/tmap-book/visual-variables.html#colors
由于您没有共享您的数据,而且我自己查找一些英国数据也不实际,因此我将在随{sf}包提供的优秀的老北卡罗来纳州shapefile上演示该技术。
作为奖励,我在选择“合适的”县名时玩得很开心。

library(sf)
library(dplyr)
library(tmap)

shape <- st_read(system.file("shape/nc.shp", package="sf")) # included with sf package

shape <- shape %>% 
  mutate(winner = case_when(NAME == "Halifax" ~ "Conservative",
                            NAME == "Wilson" ~ "Labor",
                            NAME == "Scotland" ~ "SNP",
                            NAME == "Pitt" ~ "Libdem",
                            T ~ NA)) %>% 
  filter(!is.na(winner))


tm_shape(shape) +
  tm_polygons(col = "winner",
              title = "Results",
              # here is the action!!! 
              palette = c("Conservative" = "blue", 
                          "Labor" = "red",
                          "SNP" = "yellow",
                          "Libdem" = "orange"))

62lalag4

62lalag42#

您需要创建自定义调色板:

library(tmap)
library(dplyr)

tmap_mode("view")
data("World")

states <- World %>% 
  filter(name %in% c("Austria", "Germany", "Poland", "Hungary", "Czech Rep.", "Slovakia")) %>% 
  mutate(name = factor(name, levels = c("Austria", "Germany", "Poland", "Hungary", "Czech Rep.", "Slovakia")))

# create custom color palette
custpal = c("darkred", "orange", "palegreen", "dodgerblue", "purple3", "gold")

tm_shape(states) +
    tm_polygons("name", palette = custpal)

相关问题