Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do leaflet labels support "\n" line-breaks?

Tags:

r

r-leaflet

Trying to work on my mapping/data viz skills and do a quick bubble map of where my favorite bands and genres are from. So I have a column in my data.frame titled bandnames and I made it so that every band is separated by a line break using \n. I used dplyr for this:

dplyr::summarise(BandName = paste(BandName, collapse = "\n"))

This worked perfectly when I previewed the tooltip in the RStudio view function. Here's what I mean:

enter image description here

But in leaflet, there are no linebreaks:

enter image description here

Is there any way I can fix this without making each individual band its own row (which would complicate what I'm trying to do, since I want multiple band names for each location without having multiple bubbles)?


1 Answers

You have to keep in mind leaflet renders html - so try something like

dplyr::summarise(BandName = paste(BandName, collapse = "<br>"))

and be sure to map it to popup (not label) in your leaflet call.

Or consider this example / it is built on mutate instead of summarise, the appropriate function will depend on the nature of your dataset. But the key part is using <br> as in HTML speak instead of \n as in R speak.

library(sf)
library(leaflet)

shape <- st_read(system.file("shape/nc.shp", package="sf")) %>%  # included with sf package
  st_transform(4326) %>% 
  dplyr::mutate(label = paste(CNTY_ID, NAME, sep =  "<br>"))


leaflet(shape) %>% 
  addProviderTiles("Stamen.Toner") %>% 
  addPolygons(color = "blue",
              fillColor = "red",
              popup = ~label)

enter image description here

like image 60
Jindra Lacko Avatar answered Nov 03 '25 22:11

Jindra Lacko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!