leaflet with R: add text labels

luciano picture luciano · Jul 31, 2015 · Viewed 17.7k times · Source

This code is taken from this page:

library(leaflet)
leaflet(data = quakes[1:20,]) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.character(mag))

Instead of markers, is there any way to plot mag as text labels?

Answer

symbolrush picture symbolrush · Jul 31, 2015

UPDATE

When this answer was posted, I think addLabelOnlyMarkers() was not officially included in the CRAN version. As of the 8th of January, 2018, leaflet is in version 1.1.0 on CRAN. This version has the function. No need to download a github version.

ORIGINAL ANSWER

If you have your leaflet package installed from GitHub, you can do

leaflet(data = quakes[1:20,]) %>% addTiles() %>%
  addLabelOnlyMarkers(~long, ~lat, label =  ~as.character(mag), 
                      labelOptions = labelOptions(noHide = T, direction = 'top', textOnly = T))

enter image description here


The addPopups function might be a valuable workaround if you don't want to work with the package version from GitHub. (This was the case before the official release of addLabelOnlyMarkers() in the CRAN version.)

leaflet(data = quakes[1:20,]) %>% addTiles() %>%
        addPopups(~long, ~lat, ~as.character(mag), 
        options = popupOptions(minWidth = 20, closeOnClick = FALSE, closeButton = FALSE))