包sf,如何按类别定义颜色?

Package sf, how to define color by category?

包 sf 默认分配颜色,这很好,但是如何自定义这些颜色,在我的情况下,我可以有 Pile=black, tracker=red, panel=bleu

library(sf)
dataset= data.frame(stringsAsFactors=FALSE,
          id = c("A-27-2", "A-27-2", "A-27-2"),
           x = c(143.4907147, 143.4907125, 143.4907103),
           y = c(-34.755718, -34.755645, -34.7555693),
           status = c("tracker", "Pile", "panel")
)
map <- st_as_sf(dataset, coords = c("x", "y"), crs = 4326)
plot(map["status"],pch=20,cex=0.4,key.pos=1)

编辑:第二次尝试,我添加了一个带有颜色的列,是否可以引用该列,我的真实数据框是 70K 行

library(sf)
dataset=data.frame(stringsAsFactors=FALSE,
          id = c("A-27-2", "A-27-2", "A-27-2", "A-27-2"),
           x = c(143.4907147, 143.4907125, 143.4907103, 143.4907081),
           y = c(-34.755718, -34.755645, -34.7555693, -34.7554964),
      status = c("tracker", "panel", "panel", "pile"),
       color = c("blue", "yellow", "yellow", "black")
)
map <- st_as_sf(dataset, coords = c("x", "y"), crs = 4326)
plot(map["status"],pch=20,cex=0.4,key.pos=1,col=map$color)

一切顺利

你想为此使用 ggplot,因为它更灵活。

library(ggplot2)
ggplot() + geom_sf(data = map, aes(color = status)) + 
  scale_color_manual(values = c(panel = "blue", pile = "black", tracker = "red"))

如果您必须坚持基本情节,则必须使用命名向量提供颜色:

library(sf)
dataset=data.frame(stringsAsFactors=FALSE,
                   id = c("A-27-2", "A-27-2", "A-27-2", "A-27-2"),
                   x = c(143.4907147, 143.4907125, 143.4907103, 143.4907081),
                   y = c(-34.755718, -34.755645, -34.7555693, -34.7554964),
                   status = c("tracker", "panel", "panel", "pile")
)

dataset$color <- NA
dataset$color[dataset$status == "pile"] <- "black"
dataset$color[dataset$status == "tracker"] <- "red"
dataset$color[dataset$status == "panel"] <- "blue"

map <- st_as_sf(dataset, coords = c("x", "y"), crs = 4326)
plot(map["status"],pch=20,cex=2,key.pos=1,col=map$color)
legend("bottomright", legend = c("Pile", "panel", "tracker"), 
       fill = c("black", "blue", "red"))