r - 如何使用ggplot覆盖地图和散点图?(见代码)
问题描述
我使用数据制作了一个散点图longitude
,latitude
以显示墨西哥某个地区不同教育水平的学校的位置。这是要复制的代码:
(注意:我不显示地图以节省空间,但您可以看到它们只是在您的 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
但没有令人满意的结果。任何建议和指导将不胜感激。
解决方案
推荐阅读
- android - Android Parse JSON 响应格式化输出
- html - Bootstrap 4 尝试获取此网格格式
- gitlab-ci - Gitlab CI 将文件复制到运行器主机
- jdbc - Hive JDBC开发的服务应用失败如何处理?
- python - 如何根据平均值为 pyplot 极坐标图着色
- matlab - Matlab - 串行超时但接收到的数据良好,多字节数据类型发送
- angular - 角度材料垫选择中的值必须是多选模式中的数组
- python - Numpy.allclose - 根据二进制值的相似性百分比确定容差
- react-native - 如何在本机反应中使我的 Flatlist 项目全高?
- swift - 如何将数据从 TableViewCell 中的按钮传递到视图控制器?