add st_txt?
SwampThingPaul opened this issue · 1 comments
SwampThingPaul commented
Caveats:
- I am relatively new to contributing to R-packages on github (apologize if this is the wrong way to do it).
- I am still relatively new to
sf
(transitioning fromsp
andrgeos
world). - I use
sf
to handle spatial data for analysis and produce (reproducible) maps
I was wondering if it would be worth adding a text function like raster::text(...)
? Below is a function that I put together based on code from various packages. It also includes a "halo" option to highlight added text. If this is too much or the wrong time, not a problem.
st_txt=function(x, y=NULL, labels,halo=T, col='black', hc='white', hw=0.1, ...){
if (missing(labels)) {
labels <- 1
}
if (length(labels) != nrow(x)) {
labels <- labels[1]
if (is.character(labels)) {
i <- which(labels == names(x))
if (i == 0) {
i <- 1
}
}
labels <- x[[labels]]
}
xy <- sf::st_coordinates(sf::st_centroid(x))[,1:2, drop = FALSE]
options(warn=-1)
xy <- list(x = xy[,1, drop = TRUE], y = xy[,2, drop = TRUE])
xo <- hw * graphics::strwidth('A')
yo <- hw * graphics::strheight('A')
if(halo==TRUE){
theta <- seq(pi/4, 2*pi, length.out=8*hw*10)
for (i in theta){
text( xy$x + cos(i)*xo, xy$y + sin(i)*yo, labels, col=hc, ... )
}
text(xy$x, xy$y, labels, col=col, ... )}else{
text(xy$x, xy$y, labels, col=col, ... )
}
}
Here is a working example.
library(sf)
library(USAboundaries)
utm17<-st_crs("EPSG:26917");# CRS for NAD83 UTM17
states.shp <- USAboundaries::us_states(resolution ="high")|>
as("Spatial")|>
st_as_sf()|>
st_transform(utm17)|>
subset(stusps%in%c("FL","GA","AL"))
plot(st_geometry(states.shp),col=c("grey","white","white"))
st_txt(states.shp,labels="stusps")
# A couple of variations based on different text arguments
st_txt(states.shp,labels="stusps",pos=4,offset=2,col="red",hc="yellow",font=2)
st_txt(states.shp,labels="stusps",pos=3,offset=2,col="blue")
st_txt(states.shp,labels="stusps",pos=2,offset=1.5,col="forestgreen")
st_txt(states.shp,labels="stusps",pos=1,offset=1,col="black",srt=45)