我需要遍历i个因子的迭代,并且每个因子需要在子图中绘制为一个图。我想做的是在第一个迭代栏中隐藏图例,然后使用legendgroup将所有图例捆绑在一起。这是我到目前为止所做的:
library(plotly)
library(dplyr)
mtcars %>%
mutate(vs = as.factor(vs)) %>%
group_split(cyl) %>%
lapply(function(i) {
#show.legend <- ifelse(i == 1,TRUE,FALSE)
show.legend <- if(i == 1) {TRUE} else {FALSE}
plot_ly(
data = i,x = ~gear,y = ~mpg,color = ~vs,type = "bar",legendgroup = ~vs
) %>%
layout(
barmode = "stack",showlegend = show.legend
)
}) %>%
subplot(
nrows = NROW(.),shareX = TRUE,shareY = TRUE,titleX = TRUE,titleY = TRUE,margin = 0.05
)
但这会产生错误并且没有图例:
Warning messages:
1: In if (i == 1) { :
the condition has length > 1 and only the first element will be used
如果我使用show.legend <- ifelse(i == 1,FALSE)
(上面已注释),我会得到多个图例,而不仅仅是一次。
我知道我可以执行以下操作,但是我需要循环执行此操作。
p1 <- plot_ly(blah,showlegend = TRUE)
p2 <- plot_ly(blah,showlegend = FALSE)
P3 <- plot_ly(blah,showlegend = FALSE)
subplot(p1,p2,p3)
我认为我没有正确调用i迭代。作为另一种选择,我尝试了case_when
:
show.legend <- case_when(
i == 1 ~ TRUE,i != 1 ~ FALSE
)
但是,它产生的结果与ifelse相同。