R and Leaflet: How to arrange label text across multiple lines

狂风中的少年 提交于 2019-12-29 03:30:08

问题


Suppose you have the following data frame:

cities = data.frame( name = c('Madrid','Barcelona','Sevilla'),
                 country = c('Spain','Spain','Spain'),
                 region = c('Comunidad de Madrid','Cataluña','Andalucia'),
                 data = c(100, 200, 300), 
                 lng = c(-3.683333,2.166667,-6.083333),
                 lat = c(40.433333,41.383333,37.446667))

My idea is to have a map of these cities and labels that could display some relevant information when hovering the corresponding city circles. I'd like to have the label text arranged in several lines. The very first approach below failed:

library( leaflet )

map = leaflet( cities ) %>%
addTiles() %>%
addCircles( lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000, 
          stroke = FALSE, fillOpacity = 0.8, label = paste0( cities$name,'\n', cities$region, '\n', cities$country, '\n', cities$data ) )

as well as other similar attempts. After googling a while, I found a possible solution by involving the htmltools package:

library( htmltools )
map2 = leaflet( cities ) %>%
addTiles() %>%
addCircles( lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000, 
          stroke = FALSE, fillOpacity = 0.8, 
          label = HTML( paste0( '<p>', cities$name, '<p></p>', cities$region, ', ', cities$country,'</p><p>', cities$data, '</p>' ) ) )

In this case, the information is displayed as I'd like but, within the same label, there is an entry for each city of the dataset. How could I do to have the text of a single city arranged in multiple lines? Any help would be really appreciated


回答1:


First, create a character vector of html content for each city and then wrap that in a lapply call to set the HTML attribute for correct display when defining the label attribute in adCircles

labs <- lapply(seq(nrow(cities)), function(i) {
  paste0( '<p>', cities[i, "name"], '<p></p>', 
          cities[i, "region"], ', ', 
          cities[i, "country"],'</p><p>', 
          cities[i, "data"], '</p>' ) 
})

map2 = leaflet( cities ) %>%
  addTiles() %>%
  addCircles(lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000, 
              stroke = FALSE, fillOpacity = 0.8,
              label = lapply(labs, htmltools::HTML))

map2


来源:https://stackoverflow.com/questions/43144596/r-and-leaflet-how-to-arrange-label-text-across-multiple-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!