4

I am creating a map of the world:

library(leaflet)
library(rnaturalearth)
countries <- rnaturalearth::countries110
mymap <- leaflet(countries)
mymap %>% addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1)

Is it possible to either hover over any country to see its name or to click on any country to see its name?

Thanks a lot!

Dave2e
  • 22,192
  • 18
  • 42
  • 50
user2323534
  • 585
  • 1
  • 6
  • 18

2 Answers2

8

Or, even simpler:

library(leaflet)
library(rnaturalearth)

countries <- rnaturalearth::countries110
mymap <- leaflet(countries)
mymap %>% addPolygons(stroke = FALSE, smoothFactor = 0.2, 
                      fillOpacity = 1, label = ~name)

As long as the data for the labels is part of the data frame to be plotted the ~ notation works like a charm.

TimSalabim
  • 5,604
  • 1
  • 25
  • 36
1

I figured out a solution. First, create a list of labels using library "htmltools" Then lapply it under label = . So, the final code is:

library(leaflet)
library(rnaturalearth)
library(htmltools)

countries <- rnaturalearth::countries110
mymap <- leaflet(countries)
labs <- as.list(countries$name)
mymap %>% addPolygons(stroke = FALSE, smoothFactor = 0.2, 
                      fillOpacity = 1, label = lapply(labs, HTML))
user2323534
  • 585
  • 1
  • 6
  • 18