自定义图例顺序在R传单

ljo96ir5  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(113)

我创建了一个活页Map,现在需要自定义图例的顺序。默认情况下,leaflet按字母顺序排列图例顺序。在下面的示例中,我需要图例顺序为(* 从上到下 *):夏洛茨维尔,里士满,夏洛特,罗利。如何自定义活页图例顺序?
范例:

# Import needed libraries
library(tidyverse)
library(leaflet)

# Create example dataset
aa <- data.frame(
  city = c('Richmond','Charlottesville', 'Raleigh', 'Charlotte'),
  lat = c(37.53,38.01,35.78,35.22),
  lon = c(-77.44,-78.47,-78.63,-80.84))

# Create custom colors for markers
pal <- leaflet::colorFactor(c('springgreen', 'dodgerblue', 'red', 'purple'),
                            domain = c('Richmond','Charlottesville', 'Raleigh', 'Charlotte'),
                            ordered = TRUE)

# Make map
aa %>%
  leaflet(options = leafletOptions(attributionControl = F,
                                   zoomControl = F)) %>%
  addTiles() %>%
  addProviderTiles("Esri.WorldImagery") %>%
  setView(-78.47,
          36.53,
          zoom = 7) %>%
  addCircleMarkers(
    lng = aa$lon,
    lat = aa$lat,
    label = aa$city,
    fillColor = pal(aa$city),
    fillOpacity = 1,
    color = "black",
    stroke = TRUE,
    weight = 2,
    radius = 5) %>%
  addLegend('topright', pal = pal, values = aa$city, title = 'City', opacity = 1)

字符串


的数据

  • Here is a link一个类似的问题,所以我不能去工作
    更新

根据上面链接的类似SO问题的答案,我能够重新排序图例,但是,现在图例颜色与Map上的标记颜色不匹配。
例如,在下面的图例中,夏洛特是红色的,但在Map上,夏洛特是紫色的(即,夏洛特的图例颜色应该是紫色的)。需要能够自定义重新排序图例并保持适当的颜色设置。

# Create a new grouping variable
ord <- factor(aa$city, labels = c('Charlottesville', 'Richmond', 'Charlotte', 'Raleigh'))

# Create custom colors for markers
pal <- colorFactor(c('springgreen', 'dodgerblue', 'red', 'purple'),
                            levels = ord, ordered = TRUE)

# Make map
aa %>%
  leaflet(options = leafletOptions(attributionControl = F,
                                   zoomControl = F)) %>%
  addTiles() %>%
  addProviderTiles("Esri.WorldImagery") %>%
  setView(-78.47,
          36.53,
          zoom = 7) %>%
  addCircleMarkers(
    lng = aa$lon,
    lat = aa$lat,
    label = aa$city,
    fillColor = pal(ord),
    fillOpacity = 1,
    color = "black",
    stroke = TRUE,
    weight = 2,
    radius = 5) %>%
  addLegend('topright', pal = pal, values = ord, title = 'City', opacity = 1)



^图例颜色与Map颜色不匹配(即夏洛特在Map上为紫色,但图例中为红色)。

fcg9iug3

fcg9iug31#

您需要指定factorlevels参数,而不是labels参数:

ord <- factor(aa$city, levels = c('Charlottesville', 'Richmond', 'Charlotte', 'Raleigh'))

# Create custom colors for markers
pal <- colorFactor(c('springgreen', 'dodgerblue', 'red', 'purple'), levels = ord, ordered = TRUE)

字符串


的数据

相关问题