我想根据2013年的选举结果垂直划分德国地图:
> VoteGermany2013
Party Result
1 CDU/CSU 49.4
2 SPD 30.5
3 LINKE 10.2
4 GRUENE 10.0
我正在寻找的内容非常简单:地图分为单条形图,CDU / CSU的长度为49.4%,SPD为30.5%,依此类推。它就像一个单独的栏,分为几个部分,但是以一个国家的形式。
对于地图,我使用:
library(maps)
library(mapdata)
map("worldHires","Germany")
答案 0 :(得分:10)
创建一个带有rect
的条形图,覆盖国家边框,并修剪边框周围的矩形。
library('maps')
library('mapdata')
## fill = TRUE !important
dat <- map("worldHires", "Germany", fill = TRUE)
## set up plotting window
p <- par('usr')
plot.new()
plot.window(p[1:2], p[3:4])
## make some data and calculate some useful things
pcts <- prop.table(table(sample(1:3, 20, replace = TRUE)))
xx <- range(dat$x, na.rm = TRUE)
yy <- range(dat$y, na.rm = TRUE)
zz <- diff(yy) * pcts
cols <- palette(rainbow(length(zz)))
cols <- c('red','black','gold')
## draw and color rectangles, you can do this many other ways
dy <- 0
for (ii in seq_along(zz)) {
rect(p[1], yy[1] + dy,
p[2], yy[1] + (dy <- sum(zz[1:ii])),
col = cols[ii], border = NA)
}
map('worldHires', 'Germany', col = 'black', add = TRUE)
## trim around borders
xb <- xx + c(-1, 1)
yb <- yy + c(-1, 1)
polypath(c(dat$x, NA, c(xb, rev(xb))), c(dat$y, NA, rep(yb, each = 2)),
col = 'white', rule = 'evenodd')
polypath
部分受到How can I color the ocean blue in a map of the US?
编辑:功能更易于使用,添加标签
示例数据
## examples
pcts <- prop.table(table(sample(1:3, 20, replace = TRUE)))
voteGermany2013 <- read.table(header = TRUE, text = "Party Result
1 CDU/CSU 49.4
2 SPD 30.5
3 LINKE 10.2
4 GRUENE 10.0")
功能:
evelyne <- function(x, region, labels, cols) {
op <- par(no.readonly = TRUE)
on.exit(par(op))
require('maps')
require('mapdata')
## fill = TRUE !important
dat <- map("worldHires", region, fill = TRUE)
## set up plotting window
p <- par('usr')
plot.new()
plot.window(p[1:2], p[3:4])
## calculate some useful things
xx <- range(dat$x, na.rm = TRUE)
yy <- range(dat$y, na.rm = TRUE)
zz <- diff(yy) * x
if (missing(cols))
cols <- palette(rainbow(length(x)))
## draw and color rectangles
dyy <- rep(0, length(zz))
dy <- 0
for (ii in seq_along(zz)) {
rect(p[1], yy[1] + dy, p[2], yy[1] + (dy <- sum(zz[1:ii])),
col = cols[ii], border = NA)
## label y-coordinates
dyy[ii] <- yy[1] + c(0, cumsum(zz))[ii] + zz[ii] / 2
}
map('worldHires', region, col = 'black', add = TRUE)
## trim around borders
xb <- xx + c(-1,1)
yb <- yy + c(-1,1)
polypath(c(dat$x, NA, c(xb, rev(xb))), c(dat$y, NA, rep(yb, each = 2)),
col = 'white', rule = 'evenodd')
if (!missing(labels))
text(max(xx), dyy, labels = labels, pos = 4, xpd = NA)
}
例如:
evelyne(pcts, 'Germany', cols = c('red','black','gold'))
with(voteGermany2013,
evelyne(Result / 100, 'Germany', labels = sprintf('%s (%s%%)', Party, Result)))