其他
ggplot2优雅的绘制多组配对箱线图
欢迎关注R语言数据分析指南
❝有个VIP群里的朋友今天问有没有绘制三组之间配对箱线图的代码,记得小编之前绘制过相关类型的图表,不过既然观众老爷有需求那就废话不多说直接开画;依然是以前的经典风格只不过此次在图上加上了统计分析,下面来看具体案例;
❞有需要的观众老爷欢迎加入小编的VIP群
,目前已经上传「公众号文档数据+代码约170余篇」,扫描文末尾二维码加小编微信「付费99元」后邀请进群,「由于群名额有限人满之后将不在添加新成员」,有需要的请尽早加入,早进早享受;「一定让你感受到物超所值」,本文使用R内置数据加载即可
加载R包
library(tidyverse)
library(gapminder)
library(ggsci)
library(ggprism)
library(rstatix)
library(ggpubr)
数据清洗
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=6,hide.ns = T)+
scale_size_continuous(range=c(1,3))+
facet_wrap(.~continent,nrow=1)+
scale_fill_npg()+
scale_x_discrete(guide = "prism_bracket")+
scale_y_continuous(limits = c(0,90),minor_breaks = seq(0,90,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"),
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()
❝绘图过程非常的清晰,依然是老三部曲;重点应该是数据清洗及统计分析;那么本节介绍到此结束;
❞喜欢的观众老爷欢迎分享转发
;「有需要加群的欢迎加入我的VIP交流群,99元也许能解决你的很多问题」,「加小编微信请备注来意,其它请勿扰」
小编微信
关注下方公众号下回更新不迷路
往期推荐