首页 > 解决方案 > 如何有效地绘制河流?

问题描述

我想出了一种使用 geom_path 绘制河流的方法。不知道有没有更好的办法。我不得不将数据框分成数百条“河流”。所以它非常慢。有任何想法吗?

world_map <- map_data('world') 
system("wget https://sites.google.com/site/joabelb/Home/PrincRiosBrazil.zip")
system("unzip -o PrincRiosBrazil.zip")
library(rgdal)
shapeHid <- readOGR(dsn = ".", layer = "PrincipaisRiosDoBrasil") 
shapeHid@data$id = rownames(shapeHid@data)
library(ggplot2)
shapeHid.points = fortify(shapeHid, region="id")#
shapeHid.df = merge(shapeHid.points, shapeHid@data, by="id", all=F)

listofrivers<-split(shapeHid.df, shapeHid.df$id)

myMap3 <- ggplot() +
  lapply(listofrivers, function(x) geom_path(data=x, aes(x=long, y=lat), color="gray70", linetype=1)) +
  geom_map(data = world_map, map = world_map, aes(map_id = region),
           color = 'black', fill = NA, linetype=2) +
  theme(panel.border = element_rect(fill = NA, colour = "black"))+
  theme(axis.title=element_blank())+
  scale_y_continuous(limits=c(-15,6),expand=c(0,0))+
  scale_x_continuous(limits=c(-76,-55),expand=c(0,0))
myMap3

在此处输入图像描述

标签: rggplot2gis

解决方案


如果您经常使用 shapefile,geom_path 和 geom_polygon 可以满足您的一切需求。在最近的版本中,ggplot 直接处理空间对象,因此无需使用强化和合并(可能该步骤在您的代码中花费更多时间)。这是一个使用来自 IBGE 的巴西联邦单位的 shapefile作为底图的示例:

shapeUFs <- readOGR('.', 'BRUFE250GC_SIR')
shapeHid <- readOGR('.', 'PrincipaisRiosDoBrasil') 

ggplot(shapeUFs, aes(long, lat, group = group)) +
  geom_polygon(fill = 'gray90', color = 'black') +
  geom_path(data = shapeHid, color = 'steelblue2') +
  coord_map() + theme_void()

在此处输入图像描述

与您在 ggplot 中使用的几何图形相比,形状大小(由特征数量和细节级别决定)对性能的影响更大。您可以使用 rgeos::gSimplify 减少空间多边形/线对象中的顶点数。您还可以直接在地图上绘制点:

# Simplifying the geometry of the federative units
shapeUFs.s <- rgeos::gSimplify(shapeUFs, .05, TRUE)

# Storing map in an object
riversMap <- ggplot(shapeUFs.s, aes(long, lat)) +
  geom_polygon(aes(group = group), fill = 'gray90', color = 'black') +
  geom_path(data = shapeHid, aes(group = group), color = 'steelblue2') +
  coord_map() + theme_void()

# Sampling 20 cities in Brazil
brMunics <- read.csv('https://raw.githubusercontent.com/kelvins/Municipios-Brasileiros/master/Municipios_Brasileiros.csv')
Munics <- brMunics[sample(nrow(brMunics), 20), ]

# Plotting points over the map
riversMap + geom_point(data = Munics, aes(Longitude, Latitude), color = 'red')

# If your data already have the coordinates named 'lat' and 'long',
# you can skip aes(Longitude, Latitude):
names(Munics)[6:7] <- c('lat','long')
riversMap + geom_point(data = Munics, color = 'red')

在此处输入图像描述


推荐阅读