R map switzerland according to NPA (locality)

半世苍凉 提交于 2019-11-29 02:18:13

OK, with the shapefile, we can plot things easily enough.

work.dir <- "directory_name_no_trailing slash"

# open the shapefile
require(rgdal)
require(rgeos)
require(ggplot2)
ch <- readOGR(work.dir, layer = "PLZO_PLZ")

# convert to data frame for plotting with ggplot - takes a while
ch.df <- fortify(ch)

# generate fake data and add to data frame
ch.df$count <- round(runif(nrow(ch.df), 0, 100), 0)

# plot with ggplot
ggplot(ch.df, aes(x = long, y = lat, group = group, fill = count)) +
    geom_polygon(colour = "black", size = 0.3, aes(group = group)) +
    theme()

# or you could use base R plot
ch@data$count <- round(runif(nrow(ch@data), 0, 100), 0)
plot(ch, col = ch@data$count)

Personally I find ggplot a lot easier to work with than plot and the default output is much better looking.

And ggplot uses a straightforward data frame, which makes it easy to subset.

# plot just a subset of NPAs using ggplot
my.sub <- ch.df[ch.df$id %in% c(4,6), ]
ggplot(my.sub, aes(x = long, y = lat, group = group, fill = count)) +
    geom_polygon(colour = "black", size = 0.3, aes(group = group)) +
    theme()

Result:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!