如何使用ggplot覆盖地图和散点图? (见代码)

时间:2018-05-18 07:17:32

标签: r ggplot2 graphics data-visualization

我使用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

其次,我下载ggplot的开发版本以使用geom_sf函数

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尝试了许多其他组合而没有令人满意的结果。任何建议和方向将不胜感激。

0 个答案:

没有答案
相关问题