看文獻是經(jīng)常發(fā)現(xiàn)有堆疊柱狀圖+百分比展示的例子,下面就來復現(xiàn)下這樣的圖形醉拓。下圖中的C圖擂仍。
以IMvigor210免疫治療隊列數(shù)據(jù)為例:
1.輸入數(shù)據(jù)
輸入數(shù)據(jù)rt是兩個因子變量
a <- data.frame(table(rt$risk,rt$BOR_binary))
a<- ddply(a,.(Var1),transform,percent=Freq/sum(Freq)*100)
a$label = paste0(sprintf("%.1f", a$percent), "%")
備注:plyr::ddply()
輸入data.frame返回data.frame,在計算百分比時特別好使煎饼。
2.開始畫圖
pvalue <- chisq.test(c(125,24,105,44,ncol=2))$p.value #卡方檢驗
library(plyr)
ggplot(a,aes(Var1,percent,fill=Var2))+
geom_bar(stat="identity",position = position_stack())+
scale_fill_manual(values = c("#DB423E","#008ECA"),label=c("SD/PD","CR/PR"))+
scale_y_continuous(labels = scales::percent_format(scale = 1))+ #百分比y軸
labs(x="Risk",y="Percent Weidght",
fill="")+
geom_text(aes(label=label),vjust=3,size=6,color="black")+
annotate(geom = "text",
cex=6,
x=1.5, y=105, # 根據(jù)自己的數(shù)據(jù)調(diào)節(jié)p value的位置
label=paste0("P ", ifelse(pvalue<0.001, "< 0.001", paste0("= ",round(pvalue,3)))), # 添加P值
color="black")+
theme_classic()+
theme(legend.position = "top",
legend.text = element_text(size=12),
axis.text = element_text(size=12),
axis.title = element_text(size=12))
參考鏈接: