Plotly 颜色因子中的 NSE

NSE within plotly color factors

我正在尝试设计一个函数,其中有多个输入可以控制图表的着色方式。我正在尝试使用字符串来取消要使用的 data.frame 的列,但它在 plotly 语句的 color = 参数中不起作用。非常感谢

Error in !as.name(desired_factor) : invalid argument type

require(dplyr)
require(plotly)


set.seed(42)


df <- data.frame(x = rep(LETTERS[1:5], 3), 
                 y = rexp(15, rate = 0.5),
                 z = c(rep("Adam", 5), rep("Arthur", 5), rep("Ford", 5)))
df <- arrange(df, desc(z))


df$z2 <- c(rep("a", 5), rep("b", 5), rep("c", 5))

desired_factor <- "z2"


plot_ly(df, 
        x = ~x, 
        y = ~y, 
        color = ~factor(!!as.name(desired_factor)), 
        colors = "Blues", 
        type = "bar") %>% 
  layout(barmode = "stack")

Plotly 不支持 quasiquotation。相反,它使用公式来指定列名。您有几个选择:

方案一:动态构造公式

fm <- as.formula( paste0("~factor(", desired_factor ,")") )

plot_ly(df, 
        x = ~x, 
        y = ~y, 
        color = fm,             # <-- NOTE: no ~
        colors = "Blues", 
        type = "bar") %>% 
  layout(barmode = "stack")

选项 2:构建并评估整个 plotly 表达式

ee <- rlang::expr(
  plot_ly(df, 
          x = ~x, 
          y = ~y, 
          color = ~factor(!!as.name(desired_factor)), 
          colors = "Blues", 
          type = "bar") %>% 
    layout(barmode = "stack"))

eval(ee)