[R] Help with map
Roger Bivand
Roger.Bivand at nhh.no
Fri May 4 16:40:18 CEST 2007
On Fri, 4 May 2007, Alberto Monteiro wrote:
> I have just learned how to play with map, but something weird
> (or not) is happening.
>
> Suppose I want to draw a map of two countries (that have disconnected
> components), like Argentina and Brazil.
>
> If I command:
>
> library(maps)
> library(mapdata)
> map("worldHires", c("Argentina", "Brazil"))
>
> It works fine. However, if I want to _colour_ the interior:
>
> map("worldHires", c("Argentina", "Brazil"), c("cyan", "green"), fill=T)
>
> Then the colors will be assigned to the islands (Marajo in Brazil's
> North and Tierra del Fuego in Argentina's South) and there will be
> a recycling.
>
> Is there any way to associate one color to each country?
Try:
map_poly_obj <- map("worldHires", c("Argentina", "Brazil"), plot=FALSE,
fill=TRUE)
str(map_poly_obj)
and you'll see that the component of interest is the named polygons, of
which there are 28, namely
map_poly_obj$names
So you can build a matching colours vector, or:
library(sp)
library(maptools)
IDs <- sapply(strsplit(map_poly_obj$names, ":"), function(x) x[1])
SP_AB <- map2SpatialPolygons(map_poly_obj, IDs=IDs,
proj4string=CRS("+proj=longlat +datum=wgs84"))
but
plot(SP_AB, col=c("cyan", "green"))
still misses, because some polygons have their rings of coordinates in
counter-clockwise order, so:
pl_new <- lapply(slot(SP_AB, "polygons"), checkPolygonsHoles)
slot(SP_AB, "polygons") <- pl_new
# please forget the assignment to the slot and do not do it unless you can
# replace what was there before
plot(SP_AB, col=c("cyan", "green"), axes=TRUE)
now works. Moreover, SP_AB is a SpatialPolygons object, which can be
promoted to a SpatialPolygonsDataFrame object, for a data slot holding a
data.frame with row names matching the Polygons ID values:
sapply(slot(SP_AB, "polygons"), function(x) slot(x, "ID"))
So adding a suitable data frame gets you to the lattice graphics method
spplot(SP_AB, "my_var")
Hope this helps,
Roger
>
> Alberto Monteiro
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no
More information about the R-help
mailing list