如何在R中创建分组箱图?

Dan*_* C. 8 customization plot r boxplot

我想合并分组的三个数据集,并获得只有两个框的图形,1表示A,1表示B.你能建议如何获得吗?

我正在尝试在R中创建一个分组的箱图.我有两组:A和B,在每组中我有3个子组,每个子组有5个测量值.

以下是我构建盒子图的方式,但如果有人有更好,更短或更简单的方法,我会很感激

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如何正确(组合)A和B中的框组合,并在我尝试时将轴标题固定为简单的A和B?

我喜欢类似的东西

在此输入图像描述

r2e*_*ans 10

当数据处于副格格式时,将它们分组更容易.从你的向量开始:

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)
Run Code Online (Sandbox Code Playgroud)

使用at手动控制放置,因此"可视分组"不是很健壮.(您可以使用width和/或控制它们之间的间距boxwex.)

基础R箱图

您也可以选择ggplot2:

library(ggplot2)
ggplot(DF2, aes(y, x, fill=factor(z))) +
  geom_boxplot()
Run Code Online (Sandbox Code Playgroud)

ggplot boxplot