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

时间:2017-11-24 20:16:46

标签: r plot customization boxplot

我想合并分组的三个数据集,并获得一个只有两个框的图形,一个用于A,一个用于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)

enter image description here

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

我喜欢

之类的东西

enter image description here

3 个答案:

答案 0 :(得分:7)

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

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手动控制展示位置,以便&#34;直观分组&#34;不是很强大。 (您可以使用width和/或boxwex控制它们之间的间距。)

base R boxplot

您也可以选择ggplot2

library(ggplot2)
ggplot(DF2, aes(y, x, fill=factor(z))) +
  geom_boxplot()

ggplot boxplot

答案 1 :(得分:3)

您应该使用ggplot2

ggplot() + 
  geom_boxplot(data = df, mapping = aes(col_name, value, fill=index))  + 
  theme( axis.text.x = element_blank()) +
  geom_segment(data=hline1, mapping=aes(x=1, y=-0.5, xend=3, yend=-0.5), size=2) +
  annotate("text", x = 2, y = -1, label = "A") + 
  geom_segment(data=hline1, mapping=aes(x=4, y=-0.5, xend=6, yend=-0.5), size=2) +
  annotate("text", x = 5, y = -1, label = "B")

enter image description here

答案 2 :(得分:0)

使用基数R,我认为@ r2evans解决方案是最好的。但是,对问题代码的更简单解决方法是使用选项xaxt="n"

boxplot(DF, col = rainbow(3, s = 0.5), at = c(1:3,5:7), xaxt = "n")
axis(side = 1, at = c(2,6), labels = c("A","B"))
legend("topleft", fill = rainbow(3, s = 0.5), legend = c(1,2,3), horiz = T)

这增加了格式化轴的灵活性。