由网友(月亮供电不足)分享简介:使用 plotly 的 subplots() 时如何删除图例中的重复项?How can I remove the duplicates in my legend when using plotly's subplots()? 这是我的 MWE:library(plotly)library(ggplot2)l...
使用 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
填充每个 class
组中缺失因子级别的(非 NA)虚拟值.按照 MM 的建议将 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 each class
group.
Follow M-M's suggestion setting showlegend
to TRUE
for a single group and legendgroup
to trans
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)
相关推荐
最新文章