首页 > 解决方案 > ggplot2 地图为空白

问题描述

我正在使用与加拿大统计局不同形状文件的其他脚本类似的代码。但是,我无法获得一个简单的脚本来处理省级地图。我认为问题很简单,但我看不到。

setwd("D:\\OneDrive\\lfs_stuff")
project_folder<-getwd()
data_folder<-project_folder
library(tidyverse)
#now start the map
library(rgeos)
library(rgdal)
library(maptools)
library(sp)
library(mapproj)
library(ggplot2)
#get test data
mydata<-read_csv("map_data.csv",col_types=list(col_character(),col_double()))
print(mydata)
# shape file came from this link for a digital shape file
# http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/files-fichiers/2016/lpr_000a16a_e.zip
target_url<-"http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/files-fichiers/2016/lpr_000a16a_e.zip"
url_file<-"lpr_000a16a_e.zip"
download_target<-paste0(project_folder,"/",url_file)
    download.file(target_url,download_target,mode="wb",quiet=FALSE)
    unzip(download_target,overwrite=TRUE,exdir=data_folder)
provincial_shape_file<-gsub(".zip",".shp",download_target)
provincial_shp<-readOGR(dsn=provincial_shape_file,layer="lpr_000a16a_e")
#convert it to the reqired data structure. the id vbl will contain the provincial codes
prov_base_map<-fortify(provincial_shp,region="PRUID")
map_data_1<-merge(prov_base_map,as_data_frame(mydata),by="id")
map1<-ggplot()+
geom_map(data=map_data_1,map=map_data_1,stat="identity",
aes(map_id=id,x=long,y=lat,fill=(pch),group=group),
colour="black",size=0.3)+
coord_map()
print(map1)

形状文件的下载位于脚本中。mydata 文件如下所示

"id","pch"
"10",0.667259786476859
"11",5.63186813186813
"12",2.12053571428572
"13",-0.563697857948142
"24",0.150669774230772
"35",1.15309092428315
"46",0.479282622139765
"47",1.70242950877815
"48",1.84482533036765
"59",1.96197656978394

标签: rggplot2shapes

解决方案


这是一种方法sf(尽管我认为最终的问题是没有id正确识别):

library(sf)
library(httr)
library(tidyverse)

read.csv(text='"id","pch"
"10",0.667259786476859
"11",5.63186813186813
"12",2.12053571428572
"13",-0.563697857948142
"24",0.150669774230772
"35",1.15309092428315
"46",0.479282622139765
"47",1.70242950877815
"48",1.84482533036765
"59",1.96197656978394',
         stringsAsFactors=FALSE,
         colClasses = c("character", "double")) -> xdf

# cross-platform-friendly d/l with caching built-in
try(httr::GET(
  url = "http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/files-fichiers/2016/lpr_000a16a_e.zip",
  httr::write_disk("~/Data/lpr_00a16a_e.zip"),
  httr::progress()
)) -> res

fils <- unzip("~/Data/lpr_00a16a_e.zip", exdir = "~/Data/lpr")

ca_map <- st_read(grep("shp$", fils, value=TRUE), stringsAsFactors = FALSE)
ca_map <- st_simplify(ca_map, TRUE, 10) # you don't need the coastlines to be that detailed
ca_map <- left_join(ca_map, xdf, by=c("PRUID"="id"))

ggplot(ca_map) +
  geom_sf(aes(fill = pch)) +
  viridis::scale_fill_viridis(direction=-1, option="magma") +
  coord_sf()

在此处输入图像描述

顺便说一句,即使我简化了 shapefile(为了更快地绘图),我也会四处寻找一个轻量级的 GeoJSON 版本的省份,因为你抓住的那个拥有细粒度的海岸线,而你绝对没有需要它作为合唱团。


推荐阅读