【问题标题】:R:Plotly - Creating Multiple boxplots in one graph as a groupR:Plotly - 在一个图中创建多个箱线图作为一组
【发布时间】:2016-11-16 02:08:58
【问题描述】:

我有如下 250 个 ID 的数据集

ID A_Male A_Female B_Male B_Female C_Male C_Female
1    25     75      40     60        20    80
2    30     70      50     50        80    20
3    50     50      30     70        20    80

我想在 R 中按 A、B、C 分组使用 plotly 创建箱线图。我的箱线图应如下所示(示例图)。

但我没有变量列来分组。

有没有办法可以在 R 中使用 plot_ly 包创建它? 谢谢。

【问题讨论】:

  • data.table::melt

标签: r plotly


【解决方案1】:

您可以在绘图之前使用tidyrdplyr 包对数据进行一些处理。假设您的数据框是df

library(dplyr)
library(tidyr)
library(plotly)

plot_data <- df %>%
  gather(variable, value, -ID) %>%
  separate(variable, c("group","gender"), sep = "\\_")

然后,您将使用 plot_data 使用带有新组和性别变量的 plot.ly 创建您的箱线图。

plot_ly(plot_data, x = ~group, y = ~value, color = ~gender, type = "box") 

【讨论】:

    【解决方案2】:

    您可以简单地尝试一下(其中 df 是您提供的示例数据,首先):

    df <- melt(df, id='ID')
    df[c('type', 'gender')] <- do.call(rbind, strsplit(as.character(df$variable), split='_'))
    
    plot_ly(df, x = type, y = value, color = gender, type = "box") %>% 
             layout(boxmode = "group", 
             xaxis = list(title=''), 
             yaxis = list(title='Percentage (%)'))
    

    【讨论】:

    • 非常感谢!上述两种方法都适用于这种情况
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 2019-02-27
    • 2012-09-28
    • 2020-09-10
    • 1970-01-01
    • 2020-12-03
    • 2013-01-14
    相关资源
    最近更新 更多