今天花了很多时间整理这个包的绘图函数,不得不说这个基于ggplot2的包,是真的友好,很适合初学者。可能对于熟悉ggplot2的人来说,ggpubr的存在有些多余,但这并不妨碍它成为一个优秀的R包。
接下来我主要依据变量类型,对这个包的十来种函数,近30种图形进行展示,几乎涵盖了平常看到的大多数图。这篇推文也很可能成为你见过的最详细的ggpubr中文教程。 公众号后台回复20210330,获取今天的代码和图形示例pdf。
install.packages("ggpubr")
library(ggpubr)
1. 单变量——连续型
1.1 密度图
#创建数据框
set.seed(0330)
mydata = data.frame(
group = rep(c("A", "B","C","D"), each=200),
value = c(rnorm(200, mean = 2), rnorm(200, 6),rnorm(200,2,4),rnorm(200,6,4))
)
ggdensity(mydata, x = "value", y="..density..", #或者"..count..",默认为"..density.."
fill = "lightgray",
add = "mean", #或者"median",
rug = TRUE #在图形下方添加密度线
)
ggsave("density1.pdf",width = 10,height = 10,units = "cm")
分组绘制
ggdensity(mydata, x = "value",
color = "group", fill="group", #分组
palette = "Dark2",#或者"aaas"这种ggsci包的配色形式,或者"#00AFBB"这种编码形式
add = "mean",
rug = TRUE,
alpha=0.2, #调整透明度
xlab=F,ylab = "Density",
facet.by="group", #分面
panel.labs=list(group = c("1", "2", "3", "4")), #修改每个panel的名字
title="density plot",
ggtheme=theme_bw() #可以是ggplot2中的主题类型
)
ggsave("density2.pdf",width = 13,height = 12,units = "cm")
1.2 密度图叠加正态分布
set.seed(0330)
mydata = data.frame(
group = rep(c("A", "B"), each=200),
value = c(rnorm(200, 2), rnorm(200, 6, 4))
)
ggdensity(mydata, x = "value", fill = "red") +
stat_overlay_normal_density(color = "red", linetype = "dashed")+
scale_x_continuous(limits = c(-5,20))
ggsave("density3.pdf",width = 10,height = 10,units = "cm")
分组绘制
ggdensity(mydata, x = "value", fill = "group") +
stat_overlay_normal_density(aes(color=group), linetype = "dashed")+
scale_x_continuous(limits = c(-5,20))
ggsave("density4.pdf",width = 10,height = 10,units = "cm")
分组+分面
ggdensity(mydata, x = "value", fill = "group", facet.by = "group") +
stat_overlay_normal_density(aes(color=group), linetype = "dashed")+
scale_x_continuous(limits = c(-5,20))
ggsave("density5.pdf",width = 16,height = 10,units = "cm")
1.3 直方图
gghistogram(mydata, x = "value", fill = "lightgray",
add = "mean", rug = TRUE)
ggsave("hist1.pdf",width = 10,height = 10,units = "cm")
分组绘制
gghistogram(mydata, x = "value", fill = "group",
add = "mean", rug = TRUE,
palette = c("#0