本文介绍了如何使用plotly subplots()删除重复的图例条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用plotly的subplots()时,如何删除图例中的重复项?
How can I remove the duplicates in my legend when using plotly's subplots()?
这是我的MWE:
library(plotly)
library(ggplot2)
library(tidyr)
mpg %>%
group_by(class) %>%
do(p = plot_ly(., x = ~cyl, y = ~displ, color = ~trans, type = 'bar')) %>%
subplot(nrows = 2, shareX = TRUE, titleX = TRUE) %>%
layout(barmode = 'stack')
推荐答案
使用tidyverse
的另一种解决方法.以下步骤已添加到原始MWE:
Another workaround using the tidyverse
. The following steps are added to the original MWE:
- 将
trans
列转换为因子. - 使用tidyr的
complete
来填充(非NA)虚拟值,以用于每个class
组中的缺失因子水平. - 按照M-M的建议设置,将单个组的
showlegend
设置为TRUE
,将legendgroup
的设置设置为trans
,以将子图之间的图例条目链接起来.
- Convert the
trans
column to a factor. - Use tidyr's
complete
to fill (non-NA) dummy values for the missing factor levels in eachclass
group. - Follow M-M's suggestion setting
showlegend
toTRUE
for a single group andlegendgroup
totrans
to link the legend entries between subplots.
library(plotly)
library(tidyverse)
mpg %>%
mutate_at("trans", as.factor) %>%
group_by(class) %>%
group_map(.f = ~{
## fill missing levels w/ displ = 0, cyl = first available value
complete(.x, trans, fill = list(displ = 0, cyl = head(.x$cyl, 1))) %>%
plot_ly(x = ~cyl, y = ~displ, color = ~trans, colors = "Paired", type = "bar",
showlegend = (.y == "2seater"), legendgroup = ~trans) %>%
layout(yaxis = list(title = as.character(.y)), barmode = "stack")
}) %>%
subplot(nrows = 2, shareX = TRUE, titleY = TRUE)
这篇关于如何使用plotly subplots()删除重复的图例条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!