You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R中基于条件列分组用ggplot绘制各数值列叠加密度图的方法

实现方案

以下基于tidyverse生态实现,不需要手动指定分组取值,条件列新增分类时也无需修改代码,适配大样本数据场景。

依赖加载

library(ggplot2)
library(dplyr)
# 批量出图可选
library(purrr)

模拟示例数据(可跳过直接使用自己的数据集)

set.seed(123)
# c1为条件列,取值a/b/c;c2/c3/c4为待绘图数值列
df <- data.frame(
  c1 = sample(c("a", "b", "c"), 10000, replace = TRUE),
  c2 = rnorm(10000, mean = rep(c(1,3,5), each = 10000/3)),
  c3 = rnorm(10000, mean = rep(c(2,4,6), each = 10000/3)),
  c4 = rnorm(10000, mean = rep(c(0,2,4), each = 10000/3))
)

批量绘图实现

第一步:配置参数

仅需修改这里的列名匹配你的实际数据集即可:

# 待绘图的数值列
plot_cols <- c("c2", "c3", "c4")
# 分组用的条件列名
group_col <- "c1"

第二步:批量生成图对象

这里用purrr::map实现,生成的图对象存在列表中,可按需查看或保存:

plot_list <- map(plot_cols, function(col_name) {
  ggplot(df, aes(x = .data[[col_name]], color = .data[[group_col]], fill = .data[[group_col]])) +
    # 不需要填充可以去掉fill映射、删除alpha参数
    geom_density(alpha = 0.3, adjust = 1) + 
    labs(
      title = paste(col_name, "分类密度分布"),
      x = col_name,
      y = "密度",
      color = "类别",
      fill = "类别"
    ) +
    theme_minimal()
})

第三步:查看/保存图片

  • 查看单张图:比如查看c2的密度图直接运行plot_list[[1]],c3对应plot_list[[2]],c4对应plot_list[[3]]
  • 批量保存到本地:
iwalk(plot_list, function(p, idx) {
  ggsave(
    paste0(plot_cols[idx], "_密度分布.png"),
    p,
    width = 8,
    height = 6,
    dpi = 300
  )
})

替代方案:基础循环实现

不想引入purrr的话可以用基础循环实现:

for (col in plot_cols) {
  p <- ggplot(df, aes(x = .data[[col]], color = .data[[group_col]], fill = .data[[group_col]])) +
    geom_density(alpha = 0.3) +
    labs(title = paste(col, "分类密度分布"), x = col, y = "密度") +
    theme_minimal()
  # 打印展示
  print(p)
  # 保存到本地
  ggsave(paste0(col, "_密度分布.png"), p, width = 8, height = 6, dpi = 300)
}

性能优化提示

如果数据量超过百万级,可以:

  • 给geom_density的adjust参数调大,降低平滑计算量
  • 提前按条件列分组采样,保留分布特征的前提下减少数据量

内容的提问来源于stack exchange,提问作者keenan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:39:03