❝本节来根据nature microbiology上的一张图表来绘制相似风格的图,多元素注释小提琴图,「图形内容非常的丰富包含众多的元素」,数据为随意构建无意义,整个过程仅参考。希望对各位观众老爷能有所帮助。「数据代码已经整合上传到会员交流群」,购买过小编VIP的朋友可在所加的会员群内获取下载,有需要的朋友可关注文中介绍加入VIP交流群。 ❞



注:此代码需要安装最新版ggplot2 3.5版
install.packages("ggplot2")
library(tidyverse)
library(ggh4x)

df <- read_tsv("data.xls") %>%
mutate(year=as.character(year))
df$continent <- factor(df$continent,levels = c("Asia","Americas","Europe"))
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))+
annotate("rect", xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = 41.5,
fill = "cornflowerblue", alpha = .3, color = NA)+
annotate("rect", xmin = -Inf, xmax = Inf, ymin = 80, ymax = Inf,
fill = "#FCAE12", alpha = .3, color = NA) +
geom_violin(aes(fill=continent),trim = FALSE,show.legend = F)+
geom_boxplot(width = 0.2,outliers = FALSE, staplewidth = 0.5) +
scale_y_continuous(sec.axis = sec_axis(~ ., name = ""))+
geom_hline(yintercept = 80,linetype=2)+
geom_hline(yintercept = 41.5,linetype=2)+
facet_nested_wrap(. ~ continent,
strip = strip_nested(background_x =
elem_list_rect(fill=c("#3B9AB2","#7294D4","#E6A0C4")))) +
scale_fill_manual(values = c("#3B9AB2","#7294D4","#E6A0C4"))+
labs(x=NULL,y=NULL)+
theme(axis.text.x=element_text(angle = 0,vjust=0.5,hjust=0.5,color="black"),
axis.text.y=element_text(color="black"),
plot.background = element_rect(fill="white"),
panel.background = element_rect(fill="white"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.spacing.x = unit(0,"cm"),
plot.margin=unit(c(0.5,0.5,0.5,0.5),unit="cm"))