R:Plotly - 在一个图形中创建多个箱线图作为一组
R:Plotly - Creating Multiple boxplots in one graph as a group
我有一个 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
我想在按 A、B、C 分组的 R 中使用 plotly 创建一个箱线图。我的箱线图应如下所示(示例图)。
但是我没有变量列来对其进行分组。
有没有一种方法可以使用 plot_ly 包在 R 中创建它?
谢谢
您可以在绘图之前使用 tidyr
和 dplyr
包对数据进行一些处理来完成此操作。假设你的数据框是 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")
您可以简单地尝试一下(其中 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 (%)'))
我有一个 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
我想在按 A、B、C 分组的 R 中使用 plotly 创建一个箱线图。我的箱线图应如下所示(示例图)。
但是我没有变量列来对其进行分组。
有没有一种方法可以使用 plot_ly 包在 R 中创建它? 谢谢
您可以在绘图之前使用 tidyr
和 dplyr
包对数据进行一些处理来完成此操作。假设你的数据框是 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")
您可以简单地尝试一下(其中 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 (%)'))