我有以下情节。
我想将行政区域划分为给定数目(例如20)相等的部分。
library(maps)
data(world.cities)
Pakistan <- data.frame(map("world", "Pakistan", plot = FALSE)[c("x","y")])
library(ggplot2)
p <- ggplot(Pakistan, aes(x = x, y = y)) +
geom_path(colour = 'green', linestyle = 2) +
coord_map() +
theme_bw() +
labs(x=" ", y=" ") +
theme(
panel.grid.minor = element_blank()
, panel.grid.major=element_blank()
, axis.ticks = element_blank()
, axis.text.x = element_blank()
, axis.text.y = element_blank()
, panel.border = element_blank()
)
print(p)
已编辑
makeVchopper <- function(pol){
bb = bbox(pol)
delta = (bb[2,2] - bb[2,1])/10
xmin = bb[1,1]-delta
ymin = bb[2,1]-delta
ymax = bb[2,2]+delta
choppoly = function(xmax){
readWKT(sprintf("POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))",
xmin,ymin, xmin,ymax, xmax,ymax, xmax,ymin, xmin,ymin))
}
choppoly
}
slicer <- function(pol, xmin, xmax){
bb = bbox(pol)
delta = (bb[2,2] - bb[2,1])/10
ymax = bb[2,2] + delta
ymin = bb[2,1] - delta
r = readWKT(sprintf("POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))",
xmin,ymin, xmin,ymax, xmax,ymax, xmax,ymin, xmin,ymin))
gIntersection(pol,r)
}
chop_thirds <- function(pol, fractions=c(1/3, 2/3)){
chopper = makeVchopper(pol)
bb = bbox(pol)
xmin = bb[1,1]
xmax = bb[1,2]
totalArea = gArea(pol)
chopped_area = function(x){
gArea(gIntersection(chopper(x),pol))
}
edges = lapply(fractions, function(fraction){
target = totalArea * fraction
target_function = function(x){
chopped_area(x) - target
}
uniroot(target_function, lower=xmin, upper=xmax)$root
})
xdelta = (xmax-xmin)/10
chops = matrix(c(xmin-xdelta, rep(edges,rep(2,length(edges))),
xmax+xdelta), ncol=2, byrow=TRUE)
apply(chops, 1, function(edges){
slicer(pol, edges[1], edges[2])
})
}
# Usage:
library(rgeos)
library(sp)
# sample data
pol <- readWKT("POLYGON((-180 -20, -140 55, 10 0, -140 -60, -180 -20), (-150 -20, -100 -10, -110 20, -150 -20))")
plot(pol)
# now split
parts = chop_thirds(pol)
plot(pol)
plot(parts[[1]], add=TRUE, col=1)
plot(parts[[2]], add=TRUE, col=2)
plot(parts[[3]], add=TRUE, col=3)
gArea(parts[[1]])
gArea(parts[[2]])
gArea(parts[[3]])