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

时间:2019-02-24 07:19:47

标签: r sf

Package sf默认情况下分配颜色,这很好,但是在我的情况下,如何自定义这些颜色,我可以让Pipe =黑色,tracker =红色,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)

edit:第二次尝试,我添加了一个带有颜色的列,是否可以引用该列,我的实际数据框是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)

一切都好

1 个答案:

答案 0 :(得分:2)

您希望为此使用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"))