并排绘制来自两个数据集的箱线图
plot boxplots from two datasets side by side
我有两个数据框,我想为彼此并排的分数绘制箱线图,每个数据框箱线图都有不同的颜色。
ID
score1
score 2
1
200
300
2
300
150
3
400
-100
ID
score1
score 2
200
200
300
300
300
150
400
400
-100
这类问题通常与重塑数据有关。格式应该是长格式,数据是宽格式。请参阅 this post 了解如何将数据从宽格式重塑为长格式。
但是在重塑数据之前,创建一个新列来说明该数据来自哪个数据集并绑定两个数据集。
x <- '
ID score1 score2
1 200 300
2 300 150
3 400 -100'
y <- '
ID score1 score2
200 200 300
300 300 150
400 400 -100'
df1 <- read.table(textConnection(x), header = TRUE)
df2 <- read.table(textConnection(y), header = TRUE)
dfboth <- rbind(
cbind(data = 1, df1),
cbind(data = 2, df2)
)
suppressPackageStartupMessages({
library(dplyr)
library(tidyr)
library(ggplot2)
})
bind_rows(
df1 %>% mutate(data = "1"),
df2 %>% mutate(data = "2")
) %>%
pivot_longer(starts_with("score"), names_to = "score") %>%
ggplot(aes(data, value, fill = score)) +
geom_boxplot() +
xlab("Data set")
由 reprex package (v2.0.1)
于 2022-04-29 创建
我有两个数据框,我想为彼此并排的分数绘制箱线图,每个数据框箱线图都有不同的颜色。
ID | score1 | score 2 |
---|---|---|
1 | 200 | 300 |
2 | 300 | 150 |
3 | 400 | -100 |
ID | score1 | score 2 |
---|---|---|
200 | 200 | 300 |
300 | 300 | 150 |
400 | 400 | -100 |
这类问题通常与重塑数据有关。格式应该是长格式,数据是宽格式。请参阅 this post 了解如何将数据从宽格式重塑为长格式。
但是在重塑数据之前,创建一个新列来说明该数据来自哪个数据集并绑定两个数据集。
x <- '
ID score1 score2
1 200 300
2 300 150
3 400 -100'
y <- '
ID score1 score2
200 200 300
300 300 150
400 400 -100'
df1 <- read.table(textConnection(x), header = TRUE)
df2 <- read.table(textConnection(y), header = TRUE)
dfboth <- rbind(
cbind(data = 1, df1),
cbind(data = 2, df2)
)
suppressPackageStartupMessages({
library(dplyr)
library(tidyr)
library(ggplot2)
})
bind_rows(
df1 %>% mutate(data = "1"),
df2 %>% mutate(data = "2")
) %>%
pivot_longer(starts_with("score"), names_to = "score") %>%
ggplot(aes(data, value, fill = score)) +
geom_boxplot() +
xlab("Data set")
由 reprex package (v2.0.1)
于 2022-04-29 创建