r - 在分组箱线图上放置水平线

标签 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 与框完全对齐,然后将其扩展到分组箱线图设置。

谢谢!

最佳答案

这可以使用侧面的解决方法来完成:

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

关于r - 在分组箱线图上放置水平线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64186967/

相关文章:

替换整个小标题中的值

r - 使用ggplot2在直方图上绘制置信区间

regex - 批处理文件删除具有相同变量的行

具有空值的 Highcharts 行

当我有文件名的一部分时从 R 中读取文件

python - 如何在Python中实现这个R泊松分布?

r - 如何在R中加载地理空间pdf?

r - 堆积和排名条形图

r - 将 position_dodge 与 geom_pointrange 一起使用

fortran - 在 Fortran 中读取具有未知边界的行中的整数序列