gpt4 book ai didi

r - 如何使用 plotly subplots() 删除重复的图例条目

转载 作者:行者123 更新时间:2023-12-04 02:16:24 26 4
gpt4 key购买 nike

使用 plotly 的 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 添加了以下步骤:

  • trans 列转换为因子。
  • 使用 tidyr 的 complete 为每个 class 组中的缺失因子水平填充(非 NA)虚拟值。
  • 按照 M-M 的建议设置 showlegendTRUE 单个组和 legendgroup 到 0x25184312 条目之间的子图链接。

  • 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_plot

    关于r - 如何使用 plotly subplots() 删除重复的图例条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57253488/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com