我正在尝试创建一个地图,根据一些定义的类别显示井的位置。我已经将每口井的水位相对于他们的完整记录进行了分类,将水位分为“有史以来最高”、“高于正常”、“正常”、“低于正常”、“有史以来最低”等术语。使用 tmap,我想使用以下颜色“最高”= 深蓝色、“高于正常”= 浅蓝色、“正常”=绿色、“低于正常”=黄色、“最低”来显示这些条件中的每一个-ever" = 红色
到目前为止,我已经创建了一个用于映射的 sf 文件
Library(tidyverse)
library(sf)
library(spData)
Library(tmap)
Library(tmaptools)
Run Code Online (Sandbox Code Playgroud)
我的资料
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"))
Run Code Online (Sandbox Code Playgroud)
创建用于映射的 sf 文件
test_sf <-test %>%
st_as_sf(coords = c("x","y"),crs = 27200,agr="constant")
Run Code Online (Sandbox Code Playgroud)
获取背景图
HB_map <- nz %>%
filter(Name=="Hawke's Bay") %>%
read_osm(type = "stamen-terrain")
Run Code Online (Sandbox Code Playgroud)
在地图上绘制数据
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)
Run Code Online (Sandbox Code Playgroud)
地图生成正确的颜色,但未与正确的类别相关联。我可以更改颜色的顺序,但地图并不总是包含每个类别,因此颜色会再次错误地分配(如果有意义的话)
您可以将con-column 转换为因子。级别的默认顺序将按字母顺序排列,这就是您分配颜色的方式。如果某个级别为空,它仍将包含在图例中。
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)
Run Code Online (Sandbox Code Playgroud)
(read_osm()对我不起作用..)