首页 > 解决方案 > 用 sf 在 R 中绘制点和多面体对象

问题描述

我一直在尝试绘制pointsmultipolygon sf对象都没有成功。以下是我的问题的可重现示例。

library(sf)
library(magrittr)
library(RColorBrewer)

nc <- st_read(system.file("shape/nc.shp", package = "sf")) %>% 
    st_transform(crs = 4326)
points <- data.frame(p = seq(15, 75, 15), 
                     long = c(-85, -80, -78, -75, -82), 
                     lat = c(34, 36, 37, 38, 35)) %>% 
        st_as_sf(coords = c('long', 'lat'), crs = 4326) 
points$p_cut <- cut(points$p, seq(0, 100, 20))

#plot1
plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, 
     pal = brewer.pal(5, 'Paired'))
plot(st_geometry(nc), axes = TRUE, graticule = TRUE, add = TRUE)

multipolygon不会出现,但如果我颠倒顺序:

#plot2
plot(st_geometry(nc), axes = TRUE, graticule = TRUE)
plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, 
     pal = brewer.pal(5, 'Paired'), add = TRUE)

最终情节中缺少两点和关键。

我该如何克服这些问题?我想改变对象bboxmultipolygon,以使缺失的点出现在第二个图中,但我找不到解决方法。

任何帮助表示赞赏。

编辑。

修改了 的 epsgmultipolygon以匹配pointsepsg。但问题仍然存在。

编辑2。 这很奇怪,但随机运行代码似乎会产生“正确的情节”。我使用了这个特定的顺序(从控制台复制):

> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, 
+      pal = brewer.pal(5, 'Paired'))
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, 
+      pal = brewer.pal(5, 'Paired'), add = TRUE)
> plot(st_geometry(nc), axes = TRUE, graticule = TRUE, add = TRUE)
> #plot2
> plot(st_geometry(nc), axes = TRUE, graticule = TRUE)
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, 
+      pal = brewer.pal(5, 'Paired'), add = TRUE)
> # plot1
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, 
+      pal = brewer.pal(5, 'Paired'))
> plot(st_geometry(nc), axes = TRUE, graticule = TRUE, add = TRUE)
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, 
+      pal = brewer.pal(5, 'Paired'), add = TRUE)

得到了这个:

出现缺失点之一 (-85,34) 但有重复点。钥匙也没有正确显示。似乎重复点的位置和多面体的大小也取决于绘图查看器的大小。

标签: rplotsf

解决方案


我使用了一个带有较大图范围的空白图(在这种情况下,较大的范围属于points对象)并将 thepointsmultipolygonobjects 添加到其中:

# sf object with the extent of the points object
bb_sol <- data.frame(long = c(-85, -75, -75, -85),
                     lat = c(34, 34, 38, 38)) %>% 
        st_as_sf(coords = c('long', 'lat'), crs = 4326)
# plot extent
plot(st_geometry(bb_sol), axes = TRUE, graticule = TRUE, pch = '.')
# plot the multipolygon
plot(st_geometry(nc), axes = TRUE, graticule = TRUE, add = TRUE)
# plot the points
plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, key.pos = NULL, 
pal = brewer.pal(5, 'Paired'), add = TRUE)

产生:

缺失的点出现,但没有关键。为了添加一个键,我尝试使用该.image_scale_factor()功能但没有好的结果


推荐阅读