SF映射使用inter_join添加缺失值

时间:2019-07-10 18:35:54

标签: r ggplot2 dplyr sf

请给我一个技术问题。

    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")找到区别。 我想要一张相同的地图,但是缺少的城市用红色标记。

谢谢

1 个答案:

答案 0 :(得分:0)

这很简单:

        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()