R语言 使用自定义调色板反转说明书图例值

ruarlubt  于 2023-09-27  发布在  其他
关注(0)|答案(2)|浏览(291)

我试图将StackOverflow中讨论过的两件事结合起来:

  • 如何为零以上/零以下的值创建自定义调色板;
  • 如何反转leafletOutput中的图例

我就快到了,实际多边形本身的颜色是正确的,但图例不太正确:

您可以看到,如果从下拉列表中选择2017年,则悬停在多边形上的颜色是正确的,但图例中的色标则不正确。

颜色在图例中应该在0处相遇,但目前没有。

我认为这是与逆转,因为它是正确的,如果你使用常规调色板,但我需要的传说是在降序。
我该怎么办?
可复制代码:

library(shiny)
library(leaflet)
library(tidyverse)

set.seed(999)

# Read in the countries data for the geometry
countries <- sf::st_read("https://rstudio.github.io/leaflet/json/countries.geojson")

# Modify for purposes
countries_mod <- countries %>%
  # Drop actual values
  select(-gdp_md_est, -pop_est) %>%
  # Create random example data
  mutate(
    `2017` = runif(177, -140, 80),
    `2018` = runif(177, -20, 70),
    `2019` = runif(177, -288, 1400)
  ) %>%
  # Pivot into long format for mapping
  pivot_longer(cols = c(`2017`:`2019`))
  

ui <- fluidPage(
  
  selectInput(
    inputId = "year_select",
    label = "Year",
    choices = c("2017", "2018", "2019")
  ),
  
  leafletOutput("plot", height = "500px")
   
)

server <- function(input, output) {
  
  # Filter the data by year
  Filtered_dat <- reactive({
    countries_mod %>%
      filter(name == input$year_select)
  })
  
  output$plot <- renderLeaflet({
    leaflet(countries) %>%
      addTiles()
  })

  
  observeEvent(Filtered_dat(), {
    
    # Colours for data less than 0 (use abs to get non-negative value)
    colors_negative <- colorRampPalette(c("#fe0000", "#fFc7c7"))(abs(min(Filtered_dat()$value)))
    # Colours for data greater than 0 
    colors_positive <- colorRampPalette(c("#d0f0b7", "#6dfe00"))(max(Filtered_dat()$value))
    
    # Create the palette
    pal <- colorNumeric(c(colors_negative, colors_positive), domain = Filtered_dat()$value)
    
    # Create the reversed palette 
    rev_pal <- colorNumeric(c(colors_negative, colors_positive), domain = Filtered_dat()$value, reverse = TRUE)
    
    leafletProxy("plot") %>%
      setView(0, 0, 1) %>%
      # Remove the old polygons
      clearShapes() %>%
      addPolygons(
        data = Filtered_dat(),
        label = ~value,
        fillColor = ~pal(Filtered_dat()[["value"]]),
        fillOpacity = 1,
        color = "#FEFEFE",
        weight = 1
      ) %>%
      # Remove old legend before redrawing
      clearControls() %>%
      addLegend(
        pal = rev_pal,
        values = Filtered_dat()$value,
        labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE))
      )
    
  })
}

shinyApp(ui = ui, server = server)
6tdlim6h

6tdlim6h1#

如果你想反转颜色,你应该交换颜色的正向量和负向量的顺序,rev颜色,以获得较暗的颜色作为它们的最大值和最小值,如下所示:

library(shiny)
library(leaflet)
library(tidyverse)

set.seed(999)

# Read in the countries data for the geometry
countries <- sf::st_read("https://rstudio.github.io/leaflet/json/countries.geojson")

# Modify for purposes
countries_mod <- countries %>%
  # Drop actual values
  select(-gdp_md_est, -pop_est) %>%
  # Create random example data
  mutate(
    `2017` = runif(177, -140, 80),
    `2018` = runif(177, -20, 70),
    `2019` = runif(177, -288, 1400)
  ) %>%
  # Pivot into long format for mapping
  pivot_longer(cols = c(`2017`:`2019`))


ui <- fluidPage(
  
  selectInput(
    inputId = "year_select",
    label = "Year",
    choices = c("2017", "2018", "2019")
  ),
  
  leafletOutput("plot", height = "500px")
  
)

server <- function(input, output) {
  
  # Filter the data by year
  Filtered_dat <- reactive({
    countries_mod %>%
      filter(name == input$year_select)
  })
  
  output$plot <- renderLeaflet({
    leaflet(countries) %>%
      addTiles()
  })
  
  
  observeEvent(Filtered_dat(), {
    
    # Colours for data less than 0 (use abs to get non-negative value)
    colors_negative <- colorRampPalette(c("#fe0000", "#fFc7c7"))(abs(min(Filtered_dat()$value)))
    # Colours for data greater than 0 
    colors_positive <- colorRampPalette(c("#d0f0b7", "#6dfe00"))(max(Filtered_dat()$value))
    
    # Create the palette
    pal <- colorNumeric(c(rev(colors_positive), rev(colors_negative)), domain = Filtered_dat()$value)
    
    # Create the reversed palette 
    rev_pal <- colorNumeric(c(rev(colors_positive), rev(colors_negative)), domain = Filtered_dat()$value, reverse = TRUE)
    
    leafletProxy("plot") %>%
      setView(0, 0, 1) %>%
      # Remove the old polygons
      clearShapes() %>%
      addPolygons(
        data = Filtered_dat(),
        label = ~value,
        fillColor = ~pal(Filtered_dat()[["value"]]),
        fillOpacity = 1,
        color = "#FEFEFE",
        weight = 1
      ) %>%
      # Remove old legend before redrawing
      clearControls() %>%
      addLegend(
        pal = rev_pal,
        values = Filtered_dat()$value,
        labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE))
      )
    
  })
}

shinyApp(ui = ui, server = server)

输出量:

5hcedyr0

5hcedyr02#

要反转图例中的颜色,可以定义

rev_pal <- colorNumeric(c(colors_negative,colors_positive), domain = rev(Filtered_dat()$value), reverse = TRUE)

然后你得到

相关问题