如何在 ggplot2 森林图中添加聚类水平线?

2024-01-07

我即将完成森林概要图。下面包含代码和绘图的图像。最后一个不错的步骤是将某些行聚集在一起。例如,1-4 年级的条形图应聚集在一起,并用空格将它们与“总计”和“男性”分开。本质上,所有相同颜色的条形图应聚集在一起并与其他条形图分开。我已经为此苦苦挣扎了几个小时。有任何想法吗?我编造了数据来创建这个示例图,包含在下面的代码中......

library(ggplot2)

#MADE UP DATA
test <- data.frame(
x = c("one", "two", "three","four", "five", "six","seven", "eight", "nine","ten",     "eleven", "twelve","thirteen", "fourteen"),
y   = c(4.0, 4.4, 7.1, 8.2, 2.9, 3.0, 4.0,  9.0, 11.0,  7.6, 4.4, 4.6, 4.9, 5.0 ),
yhi = c(6.0, 4.8, 7.6, 8.4, 3.3, 3.1, 4.8, 10.0, 16.0, 8.0, 4.5, 5.0, 6.9, 5.7), 
ylo = c(2.0, 4.2, 6.6, 8.0, 2.5, 2.9, 3.2,  8.0,  6.0, 7.2, 4.3, 4.2, 2.9, 4.3), 
labpos = c(17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17), 
lab = c("total","Year1","Year2","Year3","Year4","Male","Female","Infant","Child","Adult","Urban","Rural","Occupational","Non-Occupational"), 
grouping = factor(c(1,2,2,2,2,3,3,4,4,4,5,5,6,6)))


test$x <- reorder(test$x, c(14,13,12,11,10,9,8,7,6,5,4,3,2,1))



# MAKE INITIAL PLOT
a <- ggplot(test, aes(x=x, y=y, ymin=ylo, ymax=yhi, colour=grouping)) +  geom_pointrange(shape=15, size=1.2, position=position_dodge(width=c(0.1))) + coord_flip() + geom_hline(aes(x=0), lty=2) + xlab('Variable') + scale_x_discrete(breaks=NULL) + scale_y_continuous(limits = c(-1,26)) + theme_bw() 


# ADD AXIS LABELS3
a <- a + ylab("Blood lead level (ug/dL)") + xlab("") + ggtitle("Meta-Analysis Summary") + theme(legend.position="none")

# ADD LABELS FOR EACH POINT/CI
a + geom_text(data=test, aes(x = x, y = labpos, label = lab, hjust=0, fontface="italic")) 

非常感谢。


根据用户20650的建议解决了这个问题。

您需要添加缺少数据的行,以便组之间有空格。例如,使用我编写的数据集:

test3 <- data.frame(
x = c("one", "two", "three","four", "five", "six","seven", "eight", "nine","ten", "eleven", "twelve","thirteen", "fourteen", "fifteen"),
y   = c(4.0, NA, 4.4, 7.1, 8.2, 2.9, 3.0, 4.0,  9.0, 11.0,  7.6, 4.4, 4.6, 4.9, 5.0 ),
yhi = c(6.0, NA,  4.8, 7.6, 8.4, 3.3, 3.1, 4.8, 10.0, 16.0,  8.0, 4.5, 5.0, 6.9, 5.7), 
ylo = c(2.0, NA, 4.2, 6.6, 8.0, 2.5, 2.9, 3.2,  8.0,  6.0,  7.2, 4.3, 4.2, 2.9, 4.3), 
labpos = c(17, NA, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17), 
lab = c("total", "",   "Year1","Year2","Year3","Year4","Male","Female","Infant","Child","Adult","Urban","Rural","Occupational","Non-Occupational"), 
grouping = factor(c(1,1,2,2,2,2,3,3,4,4,4,5,5,6,6)))

test3$x <- reorder(test3$x, c(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 ggplot2 森林图中添加聚类水平线? 的相关文章

随机推荐