1

I am trying to design a function where there are multiple inputs on what factors can control how a chart is colored. I am trying to use a character string to desegnate the column of the data.frame to use, but it is not working within the color = paramater of the plotly statement. Many Thanks

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")
Joe
  • 349
  • 1
  • 2
  • 11

1 Answers1

2

Plotly doesn't support quasiquotation. Instead, it uses formulas to specify column names. You have a couple of options:

Option 1: Dynamically construct the formula

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")

Option 2: Construct and evaluate the plotly expression in its entirety

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)
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
  • 1
    This is great stuff. Thank you for being kind enough to show two examples on how to generate a solution. – Joe May 05 '20 at 15:36