其他
ggplot2优雅的绘制全能型箱线图
欢迎关注R语言数据分析指南
❝今天又遇到观众老爷提问如何给
❞多组箱线图添加置信区间及P值与R值
,想着可能其他朋友也有需求,那么就废话不多说直接开干,还是之前的绘图方案做了一些细微的改动,下面来看具体案例;
❝❞
有需要的观众老爷欢迎加入小编的VIP群
,目前已经上传「公众号文档数据+代码约170余篇」,扫描文末尾二维码加小编微信「付费99元」后邀请进群,「由于群名额有限人满之后将不在添加新成员」,有需要的请尽早加入,早进早享受;「一定让你感受到物超所值」,加入小编的VIP如果你有一些让我感兴趣的图表提供示例数据小编若有时间会写成推文发送
加载R包
library(tidyverse)
library(gapminder)
library(ggsci)
library(ggprism)
library(rstatix)
library(ggpubr)
library(ggpmisc)
数据清洗
df <- gapminder %>%
filter(year %in% c(1957,2002,2007),continent !="Oceania") %>%
select(country,year,lifeExp,continent)%>%
mutate(paired = rep(1:(n()/3),each=3),year=factor(year))
统计分析
df_p_val1 <- df %>% group_by(continent) %>%
wilcox_test(lifeExp ~ year) %>%
adjust_pvalue(p.col = "p", method = "bonferroni") %>%
add_significance(p.col = "p.adj") %>%
add_xy_position(x = "year", dodge = 0.8)
数据可视化
df %>%
ggplot(aes(year,lifeExp)) +
stat_boxplot(geom="errorbar",position=position_dodge(width=0.2),width=0.1)+
geom_boxplot(position=position_dodge(width =0.2),width=0.4)+
# geom_line(aes(group=paired),position = position_dodge(0.2),color="grey80") +
geom_point(aes(fill=year,group=paired,size=lifeExp,alpha=lifeExp),pch=21,
position = position_dodge(0.2))+
stat_pvalue_manual(df_p_val1,label = "p.adj.signif",label.size=5,hide.ns = F)+
scale_size_continuous(range=c(1,3))+
geom_smooth(method = "lm", formula = NULL,size=1,se=T,color="black",linetype="dashed",aes(group=1))+
stat_cor(label.y = 25,aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~"),group=1),color="black",
label.x.npc = "left")+
stat_regline_equation(label.y = 19,aes(group=1),color="red")+
facet_wrap(.~continent,nrow=1)+
scale_fill_npg()+
scale_x_discrete(guide = "prism_bracket")+
scale_y_continuous(limits = c(0,95),minor_breaks = seq(0,95,5),guide = "prism_offset_minor")+
labs(x=NULL,y=NULL)+
theme_prism(base_line_size =0.5)+
theme(plot.margin=unit(c(0.5,0.5,0.5,0.5),units=,"cm"),
strip.text = element_text(size=12),
axis.line = element_line(color = "black",size = 0.4),
panel.grid.minor = element_blank(),
panel.grid.major = element_line(size = 0.2,color = "#e5e5e5"),
axis.text.y = element_text(color="black",size=10),
axis.text.x = element_text(margin = margin(t = -5),color="black",size=10),
legend.position = "none",
panel.spacing = unit(0,"lines"))+
coord_cartesian()
❝还是熟悉的配方,在此只需要注意 「aes(group=1)」 参数,此参数只能用于「局部映射」,图中若要改为添加R值只需将「rr.label」改为「r.label」,可以看到此图包含的内容十分丰富基本涵盖了我所知的所有分析,希望对大伙有所帮助;那么本节介绍到此结束;
❞喜欢的观众老爷欢迎分享转发
;「有需要加群的欢迎加入我的VIP交流群,99元也许能解决就你的很多问题」,「加小编微信请备注来意,其它请勿扰」
小编微信
关注下方公众号下回更新不迷路
往期推荐