R中sp地图上的颜色编码空间数据点

Colour Coding spatial data points on sp map in R

我现在正在学习 R,我正不知所措地想弄清楚如何在我用 R 制作的地图上的空间数据点上定义两种颜色。 In progress map

数据框中有三个变量,x和y坐标,然后观察。 0表示没有观察到,1表示观察到。我希望将紫色分配给观察到的 (1),将红色分配给未观察到的 (0)。

这是我目前用来制作地图的代码:

plot(Bp_shp4, col = "grey", axes = TRUE, xlab = "Longtitude", ylab = "Latitude", xlim = c(-1, 35), ylim = c(35, 60), main = expression('Sampling sites for 'italic('Brachytron pretense')'有无'))

plot(Bp_hydro, pch = 20, col = "cyan", cex = 0.5, add = TRUE)

绘图(Bp_Spatial_df,pch = 20,cex = 1,add = TRUE,)

Bp_Spatial_df 是我的包含三个变量的数据框,但是如果我指定一种颜色,它只会为一种一致的颜色着色,我已经尝试将其作为一个因素,但如果没有点只是不密谋。

非常感谢任何帮助,我的任务已经完全停止,这几乎只是它的开始...

我项目中所有数据框的Str(data):

加载.CSV:

    > str(Bp_Coord)
     'data.frame':  93 obs. of  3 variables:
     $ x       : num  7.29 9.88 1.12 -3.88 22.21 ...
     $ y       : num  43.9 54 49.3 43.1 40.6 ...
     $ Observed: int  1 1 1 1 1 1 1 1 1 0 ...

**Spatial point assignment**
coords <- SpatialPoints(Bp_Coord[, c("x", "y")])
> str(coords)
Formal class 'SpatialPoints' [package "sp"] with 3 slots
  ..@ coords     : num [1:93, 1:2] 7.29 9.88 1.12 -3.88 22.21 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : NULL
  .. .. ..$ : chr [1:2] "x" "y"
  ..@ bbox       : num [1:2, 1:2] -9.12 37.21 26.46 58.62
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:2] "x" "y"
  .. .. ..$ : chr [1:2] "min" "max"
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr NA

空间点数据框代码:

Bp_Spatial_df <- SpatialPointsDataFrame(coords, Bp_Coord)
proj4string(Bp_Spatial_df) <- CRS("+proj=longlat +ellps=WGS84")

> str(Bp_Spatial_df)
Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
  ..@ data       :'data.frame': 93 obs. of  3 variables:
  .. ..$ x       : num [1:93] 7.29 9.88 1.12 -3.88 22.21 ...
  .. ..$ y       : num [1:93] 43.9 54 49.3 43.1 40.6 ...
  .. ..$ Observed: int [1:93] 1 1 1 1 1 1 1 1 1 0 ...
  ..@ coords.nrs : num(0) 
  ..@ coords     : num [1:93, 1:2] 7.29 9.88 1.12 -3.88 22.21 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : NULL
  .. .. ..$ : chr [1:2] "x" "y"
  ..@ bbox       : num [1:2, 1:2] -9.12 37.21 26.46 58.62
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:2] "x" "y"
  .. .. ..$ : chr [1:2] "min" "max"
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr "+proj=longlat +ellps=WGS84"

其他两个数据框只是shapefile。

I wish to allocate a purple colour to the observed (1) and a red colour to non-observed (0).

首先创建颜色:

cols <- c("red", "purple")

然后,由于 observed 是一个数值向量,您可以使用它来索引数据中的这些预定义颜色。但是添加 1L 使其成为 (1,2) 向量,因为索引在 R 中从 1 开始。

plot(Bp_Spatial_df, pch = 20, col = cols[Bp_Spatial_df$Observed+1L], cex = 0.5, add = TRUE)