美观的小提琴图是箱型图的升级版本,很多文章应用小提琴图为文章填色不少
文献
小提琴图
参考
代码来源Split Violin Plot for ggplot2 · GitHub
关注我们的公众号,可见详细复现Fancy violin (qq.com)
实战
我首先找到一个合适的颜色,并且定义了自己的作图主题
library(ggplot2)
library(ggsci)
library(ggpubr)
library(scales)
###自定义颜色
mypal=pal_simpsons(alpha = .6)(9)
mypal[c(1,7)]
show_col(mypal)
show_col(mypal[c(1,7)])
###自定义主题
mytheme <- theme(axis.text.x=element_text(size=12),
axis.text.y=element_text(size=12),
axis.title=element_text(size = 13),
legend.text=element_text(size=12),
legend.title=element_text(size=12),
axis.line = element_line(size=0.7),
panel.border = element_blank(),
panel.grid = element_blank())
方法一
方法一###数据生成
cell <- rep(LETTERS[1:10],400)
sp <- rep(c("normal","tumor"),time=c(2000,2000))
value <- c(rnorm(2000)+1,rnorm(2000)+2)
df <- data.frame(cell=cell,sample=sp,value=value)
###作图
ggplot(df,aes(x=cell,y = value,fill=sample))+
geom_split_violin(trim = T,colour=NA)+
geom_point(stat = 'summary',fun=mean,
position = position_dodge(width = 0.9))+
scale_fill_manual(values = c("#197EC099","#FED43999"))+
stat_summary(fun.min = function(x){quantile(x)[2]},
fun.max = function(x){quantile(x)[4]},
geom = 'errorbar',color='black',
width=0.01,size=0.5,
position = position_dodge(width = 0.9))+
theme_bw()+
mytheme+
ylab("Value")+xlab("Type")
方法二
方法二ggplot()+
geom_half_violin(
data = df %>% filter(sample=="normal"),
aes(x = cell,y = value),colour=NA,fill="#197EC099",side = "l"
)+
geom_half_violin(
data = df %>% filter(sample=="tumor"),
aes(x = cell,y = value),colour=NA,fill="#FED43999",side = "r"
)+
mytheme+
theme_bw()+
ylab("Value")+xlab("Type")+
geom_point(data = df,aes(x=cell,y = value,fill=sample),
stat = 'summary',fun=mean,
position = position_dodge(width = 0.7))+
stat_summary(data = df,aes(x=cell,y = value,fill=sample),
fun.min = function(x){quantile(x)[2]},
fun.max = function(x){quantile(x)[4]},
geom = 'errorbar',color='black',
width=0.01,size=0.5,
position = position_dodge(width = 0.7))+
stat_compare_means(data = df,aes(x=cell,y = value,fill=sample),label = 'p.signif')
总的来说,两种方法得到的结果一样,方法一依赖包装好的函数,方法二较为成熟,可以直接使用gghalves包。
网友评论