【发布时间】:2020-03-14 12:57:39
【问题描述】:
我需要循环遍历因子的 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, TRUE, 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 相同的结果。
【问题讨论】:
标签: r loops plotly legend r-plotly