我正在尝试设计一个函数,其中有哪些因素可以控制图表的着色方式有多个输入。我正在尝试使用字符串来分隔要使用的data.frame列,但在plotly语句的color =
参数内不起作用。非常感谢
!as.name(desired_factor)中的错误:无效的参数类型
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")
选项1:动态构造公式
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:完整构建和评估绘图表达式
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)