plotly 没有 facet 像 ggplot2 这样它会为每个 subplot 添加图例,或者您可以为其中一些关闭它。
这里我们没有包含所有~class 条目的层,也没有两个在class 中没有交集的图,它们的组合也涵盖了所有这些图。在这种情况下,我们可以将showlegend 设置为TRUE 用于那些特定的情节,并将其设置为FALSE 用于其余部分,还将legendgroup 设置为trans,这样我们就得到了一个独特但也完整的传说。
正如我所说,这里我们没有那种特殊情况。所以我能想到的有两种可能:
-
添加整个数据(复制整个数据框)并将All 类分配给它们。然后将其与原始数据一起绘制,但仅保留 class == All 的图例。
-
使用ggplot::facet_wrap,然后使用ggplotly 来创建plotly 对象。但是,这会导致x-axis 出现一些问题(比较ggplot 对象和plotly 对象)。
library(plotly)
library(ggplot2)
library(dplyr)
ly_plot <- . %>%
plot_ly(x = ~cyl, y = ~displ, color = ~trans,
type = 'bar', showlegend = ~all(legendC)) %>%
add_annotations(
text = ~unique(class),
x = 0.5,
y = 1,
yref = "paper",
xref = "paper",
xanchor = "middle",
yanchor = "top",
showarrow = FALSE,
font = list(size = 15))
mpg %>%
mutate(class= "_All_") %>%
rbind(.,mpg) %>%
mutate(legendC = (class == "_All_")) %>%
group_by(class) %>%
do(p = ly_plot(.)) %>%
subplot(nrows = 2, shareX = TRUE, titleX = TRUE) %>%
layout(barmode = 'stack')
#> Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large,
#> allowed maximum for palette Set2 is 8
#> Returning the palette you asked for with that many colors
p <- ggplot(data = mpg, aes(x=cyl, y=displ, fill=trans))+
geom_bar(stat="identity") +
facet_wrap(~class)
p
ggplotly(p) #seems for this we should also set "colour = trans"