Home > front end >  Border around text using geom_sf_label()
Border around text using geom_sf_label()

Time:01-14

This is my first question on this forum. I am working with map visualization in R and at the time of plotting I cannot get the expected result.

As the title suggests, I'm looking for a black border around the text. Here is my code:

library(dplyr)
library(geodata)
library(ggplot2)
library(sf)

gadm_valp_com <- gadm(country="CHL", level=3, path=tempdir()) %>%
  st_as_sf() %>%
  filter(NAME_1 == "Valparaíso")

ggplot(gadm_valp_com)   geom_sf(data = gadm_valp_com)  
  geom_sf_text(aes(label = NAME_3), size=1, family="lato", colour = "white")

Note: I tried with geom_sf_label(), however is not what I need.

Thanks in advance.

CodePudding user response:

If you want a border the same color as the text, you can just use geom_sf_label() with fill = NA.

If you want the border to be a different color than the text, you can use ggtext::geom_richtext(), specifying the label_colour argument as well as stat = "sf_coordinates" to make it behave like geom_sf_label():

library(dplyr)
library(ggplot2)
library(ggtext)
library(sf)

nc <- st_read(system.file("shape/nc.shp", package="sf"))

counties <- filter(nc, NAME %in% c("Washington", "Tyrrell", "Hyde", "Dare"))

ggplot(counties)   
  geom_sf(fill = "grey60")  
  geom_richtext(
    aes(label = NAME, geometry = geometry), 
    stat = "sf_coordinates",
    size = 14 / .pt,
    colour = "white",
    label.colour = "black",
    fill = NA,
    label.r = unit(0, "lines")
  )  
  theme_void()

  • Related