如何使用 tmap 在 R 中手动设置点的颜色

How to manually set colour of dots in R using tmap

我正在尝试根据某些定义的类别创建显示水井位置的地图。我已经根据完整记录对每口井的水位进行了分类,将水位分为 "Highest-ever"、"above-normal"、"normal"、"below-normal"、"Lowest-ever"。使用 tmap,我想使用以下颜色显示每个条件 "Highest-ever" = 深蓝色,"above-normal" = 浅蓝色,"normal"=绿色,"below-normal"=黄色, "Lowest-ever" = 红色

至此我已经创建了一个用于映射的sf文件

Library(tidyverse)
library(sf)
library(spData)
Library(tmap)
Library(tmaptools)

我的数据

test <- structure(list(well = c(3698L, 3697L, 4702L, 15001L, 1501L, 3737L, 
1674L, 5988L, 1475L, 15017L), con = c("N", "B", "H", "B", "L", 
"B", "N", "A", "N", "B"), x = c(2834091L, 2838342L, 2802911L, 
2845228L, 2834408L, 2834452L, 2838641L, 2834103L, 2803192L, 2929417L
), y = c(6166870L, 6165512L, 6125649L, 6174527L, 6161309L, 6168216L, 
6170055L, 6164397L, 6140763L, 6227467L)), row.names = c(NA, -10L
), class = c("tbl_df", "tbl", "data.frame"))

创建用于映射的sf文件

test_sf <-test %>% 
  st_as_sf(coords = c("x","y"),crs = 27200,agr="constant")

获取背景图

HB_map <- nz %>% 
  filter(Name=="Hawke's Bay") %>% 
  read_osm(type = "stamen-terrain")

在地图上绘制数据

qtm(HB_map)+ #this is part of tmap and used to draw a thematic map plot
  tm_shape(nz %>% filter(Name=="Hawke's Bay"))+ #define data source
  tm_borders(col = "grey40", lwd = 2, lty = "solid", alpha = NA)+
  tm_shape(test_sf)+  
tm_dots("con",palette=c(H='blue',A='cyan',N='green',B='yellow',L='red'),stretch.palette = FALSE,size = 0.4,shape =21)

地图生成了正确的颜色,但未与正确的类别相关联。我可以更改颜色的顺序,但地图并不总是包含每个类别,因此颜色会再次错误分配(如果这有意义的话)

您可以将 con 列转换为因子。级别的默认顺序将按字母顺序排列,这就是您分配颜色的方式。如果一个级别是空的,它仍然会包含在图例中。

test_sf$con <- as.factor(test_sf$con)

tm_shape(nz %>% filter(Name=="Hawke's Bay"))+ #define data source
  tm_borders(col = "grey40", lwd = 2, lty = "solid", alpha = NA)+
  tm_shape(test_sf[test_sf$con != "H",])+  
  tm_dots(col = "con", palette=c(A='cyan', B='yellow', H='blue',L='red',N='green'), stretch.palette = FALSE,size = 0.4,shape =21)

read_osm() 对我不起作用..)