用sf绘制R中的点和多重多边形对象

时间:2018-05-24 02:19:42

标签: r plot sf

我一直试图同时绘制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)

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

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

感谢任何帮助。

修改

修改multipolygon的epsg以匹配points epsg。问题仍然存在。

EDIT2 这很奇怪,但随机运行代码似乎产生了正确的情节&#34;。我使用了这个特定的顺序(从控制台复制):

> 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),但有重复点。钥匙也没有正确显示。似乎重复点的位置和多边形的大小也取决于绘图查看器的大小。

1 个答案:

答案 0 :(得分:0)

我使用了一个空白的绘图,其中包含较大绘图的范围(在这种情况下,更大的范围属于points对象)并添加了pointsmultipolygon个对象它:

# 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()函数,但使用no good results