如何在 R 中创建分组箱线图? [英] How to create a grouped boxplot in R?
问题描述
我想合并分组的三个数据集并获得一个只有两个框的图,1 个用于 A,1 个用于 B.您能建议如何获得吗?
I want to merge the three datasets grouped and obtain a graph with only two boxes, 1 for A and 1 for B. Can you suggest how to get that?
我正在尝试在 R 中创建一个分组的箱线图.我有 2 个组:A 和 B,在每组中我有 3 个子组,每个子组有 5 个测量值.
I'm tryng to create a grouped boxplot in R. I have 2 groups: A and B, in each group I have 3 subgroups with 5 measurements each.
以下是我构建箱线图的方式,但如果有人有更好、更短或更简单的方法,我将不胜感激
The following is the way that I constructed the boxplot, but if someone has a better, shorter or easy way to do, I'll appreciate
A1 <- c(1,2,9,6,4)
A2 <- c(5,1,9,2,3)
A3 <- c(1,2,3,4,5)
B1 <- c(2,4,6,8,10)
B2 <- c(0,3,6,9,12)
B3 <- c(1,1,2,8,7)
DF <- data.frame(A1, A2, A3, B1, B2, B3)
boxplot(DF, col = rainbow(3, s = 0.5))
axis(side = 1, at = c(2,5), labels = c("A","B"))
legend("topleft", fill = rainbow(3, s = 0.5), legend = c(1,2,3), horiz = T)
如何正确分组(联合)A 和B 中的框,并在尝试时将轴标题固定为简单的A 和B?
How can I group correctly (joint) the boxes in A and B, and fix the axis title to simple A and B as I tryed?
我想要类似的东西
推荐答案
当数据为长副宽格式时,这样分组更容易.从你的载体开始:
It's easier to group them like this when data is in a long format vice wide. Starting with your vectors:
DF2 <- data.frame(
x = c(c(A1, A2, A3), c(B1, B2, B3)),
y = rep(c("A", "B"), each = 15),
z = rep(rep(1:3, each=5), 2),
stringsAsFactors = FALSE
)
str(DF2)
# 'data.frame': 30 obs. of 3 variables:
# $ x: num 1 2 9 6 4 5 1 9 2 3 ...
# $ y: chr "A" "A" "A" "A" ...
# $ z: int 1 1 1 1 1 2 2 2 2 2 ...
cols <- rainbow(3, s = 0.5)
boxplot(x ~ z + y, data = DF2,
at = c(1:3, 5:7), col = cols,
names = c("", "A", "", "", "B", ""), xaxs = FALSE)
legend("topleft", fill = cols, legend = c(1,2,3), horiz = T)
使用at
手动控制放置,所以视觉分组"不是很健壮.(您可以使用 width
和/或 boxwex
来控制它们之间的间距.)
The use of at
manually controls the placement, so the "visual grouping" is not very robust. (You can control the spacing between them with width
and/or boxwex
.)
您也可以选择ggplot2
:
library(ggplot2)
ggplot(DF2, aes(y, x, fill=factor(z))) +
geom_boxplot()
这篇关于如何在 R 中创建分组箱线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!