R 和 Leaflet:如何跨多行排列标签文本 [英] R and Leaflet: How to arrange label text across multiple lines

查看:14
本文介绍了R 和 Leaflet:如何跨多行排列标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有以下数据框:

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,'
', cities$region, '
', cities$country, '
', cities$data ) )

以及其他类似的尝试.谷歌搜索了一段时间后,我通过 htmltools 包找到了一个可能的解决方案:

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

推荐答案

首先,为每个城市创建一个 html 内容的字符向量,然后将其包装在 lapply 调用中以设置 adCircles

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

这篇关于R 和 Leaflet:如何跨多行排列标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆