我需要遍历因子的迭代,并且每个因子都需要在子图中绘制为一个图。我想做的是在第一个迭代栏中隐藏图例,并使用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相同的结果。
您的代码中有两个问题:
i
不是,1:3
而是您当前的小标题是通过lapply进行迭代(请参见seq_along
下文)。这就是为什么您收到警告:如果if(i == 1){:条件的长度> 1,则仅使用第一个元素
showlegend
需要有一个参数plot_ly
不是layout
因为插曲始终处于layout
从一个它的情节。见?subplot
及其论点which_layout
。在绘图序列的后面找到的布局选项将覆盖在序列的前面找到的选项
我认为这是您追求的目标:
library(plotly)
library(dplyr)
tibble_list <- mtcars %>%
mutate(vs = as.factor(vs)) %>%
group_split(cyl)
lapply(seq_along(tibble_list), function(i) {
show_legend <- if (i == 1) {TRUE} else {FALSE}
plot_ly(
data = tibble_list[[i]],
x = ~ gear,
y = ~ mpg,
color = ~ vs,
type = "bar",
legendgroup = ~ vs,
showlegend = show_legend
) %>% layout(barmode = "stack")
}) %>% subplot(
nrows = NROW(.),
shareX = TRUE,
shareY = TRUE,
titleX = TRUE,
titleY = TRUE,
margin = 0.05,
which_layout = 1
)
请在此处找到一个官方示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句