我有一个数据对象,其中包含在一系列监测站获得的两种空气污染物的测量样本。我还有这些站的空间坐标。例如:
library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.7.2, PROJ 9.3.0; sf_use_s2() is TRUE
library(ggplot2)
monitoring_stations <- st_sf(
data.frame(ID = c("A", "B", "C")),
geometry = st_sfc(
st_point(c(1, 1)),
st_point(c(2, 2)),
st_point(c(3, 3))
)
)
values <- data.frame(
ID = sample(c("A", "B", "C"), size = 100, replace = TRUE),
value1 = runif(100),
value2 = runif(100)
)
(full_data <- merge(monitoring_stations, values, by = "ID"))
#> Simple feature collection with 100 features and 3 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 1 ymin: 1 xmax: 3 ymax: 3
#> CRS: NA
#> First 10 features:
#> ID value1 value2 geometry
#> 1 A 0.13221654 0.76275479 POINT (1 1)
#> 2 A 0.67336289 0.29259564 POINT (1 1)
#> 3 A 0.25384031 0.35145494 POINT (1 1)
#> 4 A 0.99337433 0.30237615 POINT (1 1)
#> 5 A 0.68685394 0.42133826 POINT (1 1)
我可以创建一个图来显示每个监测站的数据椭圆, 例如
ggplot(full_data, aes(value1, value2)) +
geom_point() +
stat_ellipse(aes(group = ID, col = ID))
我还可以显示监测站的空间位置
ggplot(full_data) +
geom_sf()
但是我想合并之前的两个图来创建一个地图 代表 1) 监测站(以点表示); 2)每个数据椭圆 监测站重叠在该地图上。如何使用 R 和 ggplot2 或任何其他包完成此任务?
创建于 2024-05-14,使用 reprex v2.0.2
积分生成对我来说没有多大意义。但是,您可以尝试添加图层
geom_point(data = ms, aes(val1, val2), colour = "red", shape = 2L)
,请参阅代码部分了解如何创建 ms
。
library(sf)
#> Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(ggplot2)
monitoring_stations <- st_sf(
data.frame(ID = c("A", "B", "C")),
geometry = st_sfc(
st_point(c(1, 1)),
st_point(c(2, 2)),
st_point(c(3, 3))
)
)
values <- data.frame(
ID = sample(c("A", "B", "C"), size = 100, replace = TRUE),
value1 = c(runif(34, 0, 2), runif(33, 1, 3), runif(33, 2, 4)),
value2 = c(runif(34, 0, 2), runif(33, 1, 3), runif(33, 2, 4))
)
full_data <- merge(monitoring_stations, values, by = "ID")
ms = cbind.data.frame(
monitoring_stations,
matrix(unlist(st_geometry(monitoring_stations)), ncol = 2L, byrow = TRUE) |>
`colnames<-`(c("val1", "val2")))
ggplot(full_data, aes(value1, value2)) +
geom_point(aes(colour = ID)) +
stat_ellipse(aes(group = ID, col = ID)) +
geom_point(data = ms, aes(val1, val2, colour = ID), shape = 2L)
请注意,重写会将代码大大缩短为几行。这是非常多余的。