The package maptools
includes new functions to label points and labels.
Line labelling
The lineLabel
function produces and draws text grobs
following the paths defined by a list of Line
objects. The sp.lineLabel
methods use this function to work easily with spplot
. Let’s use the meuse
data to illustrate how to use it:
data(meuse.grid) coordinates(meuse.grid) = ~x+y proj4string(meuse.grid) <- CRS("+init=epsg:28992") gridded(meuse.grid) = TRUE data(meuse) coordinates(meuse) = ~x+y data(meuse.riv) ## Create a SpatialLines object with ID=1 meuse.sl <- SpatialLines(list(Lines(list(Line(meuse.riv)), "1"))) library(RColorBrewer) myCols <- adjustcolor(colorRampPalette(brewer.pal(n=9, 'Reds'))(100), .85) ## label is a wrapper to build a character vector with names ## according to the SpatialLines ID's labs <- label(meuse.sl, 'Meuse River')
With textloc
you can choose where the label must be located. For example, with maxDepth
the label will start at the point where the line reaches its maximum depth:
sl1 <- list('sp.lineLabel', meuse.sl, label=labs, position='below', textloc='maxDepth', spar=.2, col='darkblue', cex=1, fontfamily='Palatino', fontface=2) spplot(meuse.grid["dist"], col.regions=myCols, sp.layout = sl1)
The default is to place the label in a stable region where the sign of the slope remains constant.
sl2 <- modifyList(sl1, list(textloc = 'constantSlope')) spplot(meuse.grid["dist"], col.regions=myCols, sp.layout = sl2)
But you can define the label location with a numeric index relative to the line length:
sl3 <- modifyList(sl1, list(textloc = 140, position='above')) spplot(meuse.grid["dist"], col.regions=myCols, sp.layout = sl3)
There is a more sophisticated example in the Spatial Data chapter of my forthcoming book.
Point labelling
This package already provided the pointLabel
function with optimization routines to find good locations for point labels without overlaps. This function, useful for base graphics, has been adapted to work with lattice
graphics and with the spplot
functions.
You will find the panel.pointLabel
to use with xyplot
and the rest of the lattice
family:
library(maptools) library(lattice) n <- 15 x <- rnorm(n)*10 y <- rnorm(n)*10 labels <- as.character(round(x, 5)) myTheme <- list(add.text=list( cex=0.7, col='midnightblue', fontface=2, fontfamily='mono')) xyplot(y~x, labels=labels, par.settings=myTheme, panel=function(x, y, labels, ...){ panel.xyplot(x, y, ...) panel.pointLabel(x, y, labels=labels, ...) })
And there is the sp.pointLabel
method to be combined with spplot
:
data(meuse.grid) coordinates(meuse.grid) = ~x+y proj4string(meuse.grid) <- CRS("+init=epsg:28992") gridded(meuse.grid) = TRUE library(RColorBrewer) myCols <- adjustcolor(colorRampPalette(brewer.pal(n=9, 'Reds'))(100), .85) pts <- spsample(meuse.grid, n=15, type="random") ## Let's print the name of some R authors Rauthors <- readLines(file.path(R.home("doc"), "AUTHORS"))[9:28] someAuthors <- Rauthors[seq_along(pts)] sl1 <- list('sp.points', pts, pch=19, cex=.8, col='midnightblue') sl2 <- list('sp.pointLabel', pts, label=someAuthors, cex=0.7, col='midnightblue', fontfamily='Palatino') spplot(meuse.grid["dist"], col.regions=myCols, sp.layout=list(sl1, sl2))
There is a more sophisticated example in the Spatial Data chapter of my forthcoming book.
carlos fernandez dijo:
their contribution is very valuable, thanks.
I am developing a thesis project on the regional frequency analysis, well I am on stage mapping using the kriging spplot as follows.
spplot(kriging_map_GLS,”var1.pred”,col.regions=terrain.colors(50),sp.layout=list(pts,norte,escala,tex1,tex2,tex3,border,lago),scales=list(draw=T))
me brilliant functional, what I is question of form, so that the polygon called “lake” has any fill color because default me graphical environment black color without filling.
“lago” is a polygon shapefile that represents the lake.
I hope your help, thank you.
Oscar Perpiñán Lamigueiro dijo:
Hola Carlos,
Cada uno de los elementos de la lista
sp.layout
es, a su vez, una lista cuyo primer componente es la función que servirá para dibujar el objeto (segundo elemento). Por tanto, debo suponer que lago es una lista de la formalago=list('sp.polygons', lagoSHP)
, dondelagoSHP
es el shapefile. En esta lista puedes añadir más elementos que servirán como argumentos para la funciónsp.polygons
. En tu caso te interesa el argumentofill
que controla el color de relleno de los polígonos. Por tanto, podrías escribir algo comolago=list('sp.polygons', lagoSHP, fill='yellow')
.Saludos.
carlos fernandez dijo:
Hola Oscar,
agradecido por tu respuesta, me ha sido de gran ayuda me la pase 1 día tratando de insertar un polígono con relleno para representar un lago, bueno lo había logrado generando un raster con forma del lago..pero el archivo se me hizo muy pesado. el comando que me recomendaste es mas ligero y manipulable que funciona genial.
Quisiera consultarte como podría controlar los labels o etiquetas de los contornos o curvas de nivel, a que me acote cada cierto intervalo y el tamaño de lo textos si fuera posible, porque cuando genero automáticamente me sale textos sobrepuestos. Asi mismo el control de las leyendas que hasta el momento no encontre información ni de como insertarlo. el comando que estoy utilizando es:
spplot(kriging_map_OLS,”var1.pred”,col.regions=terrain.colors(50),
sp.layout=list(pts_est,norte,escala,tex1,tex2,tex3,border,lago,tex4),
scales=list(draw=T),contour=T,labels=TRUE,pretty=TRUE,col=’brown’,main=’Mapeo de Indice de Inundación por Kriging Ordinario’)
Nuevamente gracias Oscar por todo los aportes.
Saludos.
Oscar Perpiñán Lamigueiro dijo:
Hola,
El método
spplot
para estos objetos está construido en base alevelplot
del paquetelattice
. Lo mejor es que consultes la ayuda de esta función. En particular, te interesa lo que Deepayan Sarkar explica sobre los argumentoscuts
ylabels
.Saludos.
romunov dijo:
That’s great! How would one handle overlap on lines? For instance, I’m trying to label some custom contour lines, but some values may overlap. Would be great if one could “throw labels around” a bit.
Oscar Perpiñán Lamigueiro dijo:
You could try the textloc argument. You can choose between ‘constantSlope’,
‘minSlope’ or ‘maxDepth’, and it can also be the numeric index of the location. On the other hand, you may play with different values for spar or with position=’above’ or position=’below’. Take a look at the examples of the help page for details.