R map switzerland according to NPA (locality)

2019-01-23 19:10发布

问题:

I plan to do a survey in Switzerland. NPA will be asked.

NPA (postal codes) contains 4 number.

  • For instance 1227 is the NPA of Carouge (part of canton Geneva - Switzerland).
  • For instance 1784 is the NPA of Courtepin (part of canton Fribourg -Switzerland).
  • etc.

I would like to know how to represent all observation (about 1500) on a map. I was thinking using ggplot as I use it for other graphs (I think ggplot is "beautiful"). However, I'm open to any other suggestion.

Here are some fake data: http://pastebin.com/HsuQnLP3

The output for the swiss map should be a bit like that USA map (credit:http://www.openintro.org)

Update:

I've tried to create some code :

library(sp)
test <-  url("https://dl.dropboxusercontent.com/u/6421260/CHE_adm3.RData")
print(load(test))
close(test)

gadm$NAME_3
gadm$TYPE_3

But it seems http://gadm.org/ doesn't provide the NPA of the communes...

New update:

I've find (thanks @yrochat) a shapefile with NPA: http://www.cadastre.ch/internet/cadastre/fr/home/products/plz/data.html

I'ts the ZIP file called : Shape LV03

Then I've tried

library("maptools")
swissmap <- readShapeLines("C:/Users/yourName/YourPath/PLZO_SHP_LV03/PLZO_PLZ.shp")
plot(swissmap)
data <- data.frame(swissmap)
data$PLZ #the row who gives the NPA

As I have the PLZ on a shapefile, how do i color my observation on the map? I provided some fake data on data http://pastebin.com/HsuQnLP3

Thanks

回答1:

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:



标签: r maps ggplot2