首页 > 解决方案 > 如何使用ggplot覆盖地图和散点图?(见代码)

问题描述

我使用数据制作了一个散点图longitudelatitude以显示墨西哥某个地区不同教育水平的学校的位置。这是要复制的代码:

(注意:我不显示地图以节省空间,但您可以看到它们只是在您的 R 会话中复制、粘贴和运行)

library(foreach)
library(forcats)
library(ggplot2)
library(dplyr)
library(stringr)
library(raster)
library(readr)
library(reshape2)
##Load csv file
gto<- read_csv(sprintf("http://fs.planeacion.sep.gob.mx/cct/cct11.csv"))

##Educational levels (this is how levels are ordered from min to max)
nivel_ed <- c("Primaria", "Secundaria", "Bachillerato", "Superior")

##Plot
    gtomap <- subset(gto, select=c(longitud, latitud, nnivel)) %>%
        filter(nnivel%in%c("PRIMARIA", "SECUNDARIA", "BACHILLERATO", 
        "PEDAGOGICA, UNIVERSITARIA O TECNOLOGICA", "PROFESIONAL")) %>%
        mutate(nnivel= case_when(nnivel== "PEDAGOGICA, UNIVERSITARIA O TECNOLOGICA" ~ "Superior",
            nnivel=="PROFESIONAL" ~ "Superior", 
            nnivel=="SECUNDARIA" ~ "Secundaria",
            nnivel=="PRIMARIA" ~ "Primaria",
            nnivel=="BACHILLERATO" ~ "Bachillerato")) %>% 
        mutate(nnivel= factor(nnivel, levels=nivel_ed)) %>%
        melt(id =c("longitud","latitud"))  %>% 
        mutate(value= factor(value, levels=nivel_ed)) %>%
        ggplot(aes(x = longitud, y = latitud, col= value)) +
        geom_point() +
        theme(legend.title=element_blank()) +
        labs(x = "", y="")

    gtomap ##To see the scatterplot

其次,为了使用geom_sf功能,我下载了ggplot的开发版

devtools::install_github("tidyverse/ggplot2")

第三,我下载地图

mapgto <- sf::read_sf("http://geoinfo.iplaneg.net/geoserver/wms/kml?layers=geonode%3Amgm_gto2010&mode=download", quiet=T)
map <- data.frame(mapgto) 

地图可以直接调用:

ggplot() + 
geom_sf(data=map)

现在,我尝试使用以下方法覆盖这些对象:

gtomap + geom_sf(data=map)

但是会抛出这个错误:

Error in FUN(X[[i]], ...) : object 'longitud' not found

我尝试了许多其他组合使用geom_sf但没有令人满意的结果。任何建议和指导将不胜感激。

标签: rggplot2graphicsdata-visualization

解决方案


推荐阅读