如何将此自定义调色板函数传递给'n'参数?

我正在使用随附的R代码在R中创建自定义调色板,该调色板将根据级别数返回十六进制值。附带的代码可以正常工作,但是我很难理解该代码如何理解输入向量中的级别数。 “ N”是函数中函数内部的参数(create_pal中的check_pal_n),但是“ n”不是您可以传递给“ create_pal”的参数之一。

显然,该代码有效,但是我想更好地理解它的工作方式。任何帮助表示赞赏!

library(tidyverse)

# create a labeled list of colors
custom_color_hexcodes <- c(
  `blue`  = "#002F6C",`red`  = "#BA0C2F",`light blue`  = "#A7C6ED",`medium blue`  = "#006789",`dark red`  = "#631032",`web blue` = "#205493",`rich black`  = "#212721",`dark grey` = "#6C6463",`medium grey`= "#8C8983",`light grey`= "#CFCDC9")

# wrap that list in a callable function
custom_cols <- function(...) {
  cols <- c(...)
  if (is.null(cols))
    return (custom_color_hexcodes)
  custom_color_hexcodes[cols]
}


# There are 10 colors,so our max number of colors will be 10.
check_pal_n <- function(n,max_n) {
  if (n > max_n) {
    warning("This palette can handle a maximum of ",max_n," values.","You have supplied ",n,".")
  } else if (n < 0) {
    stop("`n` must be a non-negative integer.")
  }
}


custom_pal <- function(fill=TRUE){
  colors <- custom_color_hexcodes
  if (fill){
    max_n <- 9
    f <- function(n) {
      check_pal_n(n,max_n)
      if (n == 1L) {
        i <- "blue"
      } else if (n == 2L) {
        i <- c("blue","red")
      } else if (n == 3L) {
        i <- c("blue","red","light blue")
    } else if (n == 4L) {
      i <- c("blue","light blue","dark red")
    } else if (n %in% 5:6) {
      ## 20120901_woc904
      i <- c("blue","dark red","dark grey","light grey")
    } else if (n == 7L) {
      # 20120818_AMC820
      i <- c("blue","light grey","medium blue")
    } else if (n >= 8L) {
      # 20120915_EUC094
      i <- c("blue","medium blue","rich black")
    }
    unname(colors[i][seq_len(n)])
  }
} else {
  max_n <- 9
  f <- function(n) {
    check_pal_n(n,max_n)
    if (n <= 3) {
      i <- c("blue","light blue")
    } else if (n %in% 4:5) {
      # i <- c("blue","dark red")
      i <- c("blue","dark grey")
    } else if (n == 6) {
      # 20120825_IRC829
      i <- c("blue","light grey")
    } else if (n > 6) {
      # 20120825_IRC829
      i <- c("blue","rich black","web blue","medium grey")
      }
      unname(colors[i][seq_len(n)])
    }
  }
  attr(f,"max_n") <- max_n
  f
}


scale_colour <- function(...) {
  discrete_scale("colour","custom_cols",custom_pal(),...)
}

scale_fill <- function(...) {
  discrete_scale("fill",...)
}
everaining 回答:如何将此自定义调色板函数传递给'n'参数?

假设create_palcustom_pal

custom_pal函数返回一个函数(在f函数中内部名为custom_pal),该函数将带有一个参数n。>

https://ggplot2.tidyverse.org/reference/discrete_scale.html解释了discrete_scale函数:您将其传递给“一个调色板函数,当使用单个整数参数(刻度中的级别数)调用该调色板函数时,该函数会返回它们应采用的值。”在这种情况下,将传递custom_pal返回的函数。

ggplot将为您提供带有适当参数的函数。

本文链接:https://www.f2er.com/3158960.html

大家都在问