在分组的箱线图中放置水平线

时间:2020-10-03 17:22:17

标签: r ggplot2 line boxplot

我正在尝试使用以下基本代码制作箱形图:

design=c("Red","Green","Blue")
actions=c("1","2","3","4","5","6","7","8")
proportion=(seq(1:240)+sample(1:500, 240, replace=T))/2000
df=data.frame(design, actions , proportion)

ggplot(df, aes(x=actions, y=proportion, fill=design)) + 
  geom_boxplot()+
  xlab(TeX("group"))+
  ylab("Y value")+
  ggtitle("Y values for each group stratified by color")

产生这样的东西: Group boxplot

我想为每组不同的“真实” Y值添加水平线。

有人对此有任何提示吗?我不知道如何提取每组盒子的宽度,否则我可以使用geom_segment。

这是一个具有未分组箱形图的MWE:

dBox <- data.frame(y = rnorm(10),group="1")
dBox=rbind(dBox,data.frame(y=rnorm(10),group="2"))
dLines <- data.frame(X =c(-0.36, 0.015),
                     Y = c(0.4, -0.2),
                     Xend = c(0.-0.015, 0.36),
                     Yend=c(0.4, -0.2),
                     group = c("True", "True"),
                     color = c("black", "red"))

ggplot(dBox, aes(x=0, y=y,fill=group)) +
  geom_boxplot(outlier.shape = 1)+ 
  geom_segment(data = dLines, aes(x = X, xend = Xend, y = Y, yend = Yend),color="red",size=1.5,linetype=1) +
  theme(legend.background = element_rect(fill = "white", size = 0.1, linetype = "solid", colour = "black"))

这将产生如下内容:Simple boxplot with red horizontal lines for true values

但是,很难使geom_segments与框精确对齐,然后将其扩展到分组框图设置。

谢谢!

2 个答案:

答案 0 :(得分:2)

这可以通过以下方面来解决:

lines = data.frame(actions = 1:8, proportion=abs(rnorm(8)))

design=c("Red","Green","Blue")
actions=c("1","2","3","4","5","6","7","8")
proportion=(seq(1:240)+sample(1:500, 240, replace=T))/2000
df=data.frame(design, actions , proportion)

lines = data.frame(actions = 1:8, proportion=abs(rnorm(8)))

p = ggplot(df, aes(x=actions, y=proportion, fill=design)) + 
  geom_boxplot()+
  xlab("group")+
  ylab("Y value")+
  ggtitle("Y values for each group stratified by color") +
  facet_grid(~actions, scale='free_x') +
  theme(
    panel.spacing.x = unit(0, "lines"), 
    strip.background = element_blank(),
    strip.text.x = element_blank())

p + geom_hline(aes(yintercept = proportion), lines)

您可能会去掉各个小平面之间的空间,以使其看起来更像您的预期。

感谢@ eugene100hickey指出如何消除刻面之间的间距。

enter image description here

答案 1 :(得分:1)

theme(panel.spacing.x)可以删除那些讨厌的行:

p + geom_hline(aes(yintercept = proportion), lines) +
    theme(panel.spacing.x = unit(0, "lines"))

enter image description here