绘制堆叠条形图,并在组间添加连线标注,可使得组间比例变化对比更加明显。
本篇文章主要参考自《学习践行者》。
library(tidyverse)
library(ggpubr)
library(ggsci)
#创建数据集
da <- data.frame(ER=c(rep("a",7),rep("b",7)),
group=c(6:0,6:0),
value=c(4,7,39,23,11,4,12,9,5,18,17,35,5,12))
da$ER <- factor(da$ER,levels = c("a","b"),labels = c("72h ER<70% \n (N=163)", "72h ER≥70% \n (N=171)"))
da$group <- factor(da$group)
#绘制堆叠条形图
p <- ggplot(da,aes(x=ER,y=value,fill=group)) +
geom_bar(stat="identity" , width=0.4, position = position_stack()) +
scale_y_continuous(breaks=seq(0,100,by=10))+ #修改y轴刻度
geom_text(aes(label = value), #添加标签
position = position_stack(vjust = 0.5), # 让文本垂直居中堆叠
size = 4, color = "white") + # 可以调整字体大小和颜色
theme_classic2()+
scale_fill_nejm()+
labs(x=" ", y="percentage of patients(%)", fill = "Modified Rankin Scale Score") +
theme(legend.position = "top", legend.title=element_text(face = "bold", size = 12)) +
guides(fill=guide_legend(nrow=1))+ #修改图列
coord_flip() #旋转x和y轴
# 提取图形的坐标轴数据
gg_obj <- ggplot_build(p)
# 提取数据
bar_data <- gg_obj$data[[1]]
bar_1 <- bar_data %>%
filter(x==1) %>%
select(ymax,xmax) %>%
rename(xvalue=xmax) %>%
mutate(group=1:7)
bar_1_1 <- data.frame(ymax=0, xvalue=1.2, group=0)
bar_2 <- bar_data %>%
filter(x==2) %>%
select(ymax,xmin) %>%
rename(xvalue=xmin) %>%
mutate(group=1:7)
bar_2_1 <- data.frame(ymax=0, xvalue=1.8, group=0)
#合并数据集
bar <- rbind(bar_1_1,bar_1,bar_2_1,bar_2)
bar$group <- factor(bar$group)
#绘制折线图
ggplot(data=bar,aes(x=xvalue,y=ymax,group=group))+
geom_line(col="blue",alpha=0.3)+
theme_classic2()+
coord_flip()
p1 <- p + geom_line(data=bar,aes(x=xvalue,y=ymax,group=group),col="blue",alpha=0.3)
p1
ggsave(p1,filename="bar.png",width = 7,height = 5,dpi=400)
得到结果: