首页 > 解决方案 > sf map 使用 inter_join 添加缺失值

问题描述

我有一个技术问题请教你。

    read_sf("map.shp")  %>% mutate(Groups = as.factor(Groups)) %>% 
        mutate(Groups = factor(Groups, levels = c(paste0(1:23)))) %>%
        left_join(data, by = "cities_code") %>%
# Show map with cities border
      ggplot() +
        geom_sf(aes(fill = Groups),  size = 0.4) +
# Color the different Groups, here 23 colors
        stat_sf_coordinates(aes(size = observation)) +
# Put point with the size of my number of observations
        scale_radius(range = c(1, 6)) +
        geom_sf(fill = "transparent", color = "gray20", size = 1, data = . %>% group_by(Groups) %>% summarise()) +
# Show the border of my Groups
        theme_bw()

这张地图正是我想要的。它代表按地区(“组”)细分的一个州的城市。但是我map.shp和我之间data有50个城市的差异,因为这些城市没有观察(所以没有“ stat_sf_coordinates(aes(size = observation))”)。

我可以找到不同之处anti_join(data, by = "cities_code")。我想要相同的地图,但请用红色标出缺失的城市。

谢谢

标签: rggplot2dplyrsf

解决方案


这很简单:

        read_sf("map.shp")  %>% mutate(Groups = as.factor(Groups)) %>% 
            mutate(Groups = factor(Groups, levels = c(paste0(1:23)))) %>%
            left_join(data, by = "cities_code") %>%
          ggplot() +
            geom_sf(aes(fill = Groups),  size = 0.4) +
            stat_sf_coordinates(aes(size = observation)) +
            scale_radius(range = c(1, 6)) +
##

geom_sf(fill = "red", color = "gray40", size = 0.4, data = . %>% anti_join(data, by = "cities_code")) +

##
            geom_sf(fill = "transparent", color = "gray20", size = 1, data = . %>% group_by(Groups) %>% summarise()) +
            theme_bw()

推荐阅读