如何使用 plotly subplots() 删除重复的图例条目 [英] How to remove duplicate legend entries w/ plotly subplots()

查看:27
本文介绍了如何使用 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 填充每个 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) 

这篇关于如何使用 plotly subplots() 删除重复的图例条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆