首先整体展示下绘制密度曲线的函数ggdensity的用法
ggdensity(data, x, y = "..density..", combine = FALSE, merge = FALSE, color = "black", fill = NA, palette = NULL, size = NULL, linetype = "solid", alpha = 0.5, title = NULL, xlab = NULL, ylab = NULL, facet.by = NULL, panel.labs = NULL, short.panel.labs = TRUE, add = c("none", "mean", "median"), add.params = list(linetype = "dashed"), rug = FALSE, label = NULL, font.label = list(size = 11, color = "black"), label.select = NULL, repel = FALSE, label.rectangle = FALSE, ggtheme = theme_pubr(), ...)
data所需的数据框 dataframe
x进行作图所需的数据
y设置为密度/数量(density/count)
combine对于多个变量的数据是否分面
merge对于多个变量的数据是否合并,默认是FALSE
color, fill线条颜色与填充色
palette自定义颜色画板
size设置点和轮廓的大小
linetype线条类型
alpha透明度设置
title设置标题
xlab设置x轴标题
ylab设置y轴标题
facet.by设置分组分面
panel.labs设置分面各组的标题
short.panel.labs是否缩写分面标题,逻辑值,默认是TRUE
add添加均值线或中位数线,选项有"mean" or "median"
add.params给add参数的对象添加其他参数/属性
rug逻辑值,若为TRUE,在X轴上添加地毯线显示样本的分布label设置列标签
font.label设置标签字体
repel逻辑值,是否使用ggrepel避免字体重叠
label.rectangle是否给标签添加方框
ggtheme设置画图主题
set.seed(4321)
df1 <- data.frame(sex=factor(rep(c("F", "M"), each=200)), weight=c(rnorm(200, 55), rnorm(200, 58)))
str(df1)
ggdensity(df1, x = "weight", fill = "lightgray", add = "mean", rug = TRUE)
# 基础样式,添加均值线和地毯线,密度图展示不同性别分组下体重的分布,X轴为体重,Y轴为自动累计的密度
ggdensity(df1, x="weight", add = "mean", rug = TRUE, color = "sex", fill = "sex", palette ="lancet")
#根据分组设置线条颜色和填充,色板选择的柳叶刀
ggdensity(df1, x="weight", add = "mean", rug = TRUE, color = "sex", fill = "sex", palette = "npg") + xlim(55,60)
限定x轴取值范围为55-60
ggdensity(df1, #数据集
x = "weight", #x轴向量
facet.by = "sex", #分面依据向量
linetype = "dashed",#选择线型
add = "mean", #均值线
rug = TRUE, #是否添加地毯线
color = "sex", #颜色分组选择
fill = "sex", #填充颜色分组
palette = "npg")#色板
ggdensity(df1, #数据集
y = "..count..",#纵坐标改为了计数
x = "weight", #x轴向量
linetype = "dotted",#选择线型
add = "mean", #均值线
rug = TRUE, #是否添加地毯线
color = "sex", #颜色分组选择
fill = "sex", #填充颜色分组
palette = "npg")#色板