首页 > 解决方案 > 添加到 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))

layout(matrix(1:2, ncol = 2), widths = c(1, lcm(2)))
# 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)
# plot the key
.image_scale_factor(levels(factor(points$p_cut)), col = brewer.pal(5, 'Paired'), 
                    key.length = lcm(8), key.width = lcm(2), key.pos = 4, 
                    at = 1:length(levels(points$p_cut)))

在没有点对象的情况下应该可以工作:

layout(matrix(1:2, ncol = 2), widths = c(1, lcm(2)))
# sf object with the extent of the points 
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 the 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 key
.image_scale_factor(levels(factor(points$p_cut)), col = brewer.pal(5, 'Paired'), 
                        key.length = lcm(8), key.width = lcm(2), key.pos = 4, 
                        at = 1:length(levels(points$p_cut)))

即使只有点被绘制都再次失败:

layout(matrix(1:2, ncol = 2), widths = c(1, lcm(2)))
# plot the points
plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, key.pos = NULL, pal = brewer.pal(5, 'Paired'))
# plot the key
.image_scale_factor(levels(factor(points$p_cut)), col = brewer.pa(5, 'Paired'), key.length = lcm(8), key.width = lcm(2), key.pos = 4, at = 1:length(levels(points$p_cut)))

它给出了与带有此错误消息的第一张图像相同的输出:

par(opar[-desel]) 中的错误:el valor especificado del parámetro del gráfico "pin" es inválido

怎么了?为什么在绘制points对象和键时它以错误结尾?

标签: rplotsf

解决方案


添加reset = FALSE似乎有效:

layout(matrix(1:2, ncol = 2), widths = c(1, lcm(2)))
# plot the points
plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, key.pos = NULL, pal = brewer.pal(5, 'Paired'), reset = FALSE)
# plot the key
.image_scale_factor(levels(factor(points$p_cut)), col = brewer.pal(5, 'Paired'), key.length = lcm(8), key.width = lcm(2), key.pos = 4, at = 1:length(levels(points$p_cut)))

推荐阅读