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

如何基于R语言数据集绘制带指定垂直线的分组密度图?

解决方法:给两组别绘制密度图并添加垂直线

首先先修正你提供的数据集代码里的两处小问题,确保数据框能正常生成:

  • 变量名拼写错误:start_date → startdate
  • group列长度不匹配:调整重复次数让它和其他列长度一致(总10000行)

修正后的数据集代码:

set.seed(1)
startdate <- as.Date('2000-01-01')
enddate <- as.Date('2000-01-10')
Data <- data.frame(
  id = rep((1:1000), 10),
  group = rep(c("0","1"), 5000),  # 调整重复次数匹配总行数
  IV = sample(1:100, 10000, replace = TRUE),  # 指定总长度
  DV = sample(c("1", "0"), 10000, replace = TRUE),
  date = as.Date( sample(as.numeric(startdate): as.numeric(enddate), 10000, replace = T), 
                  origin = '1970-01-01')
)

接下来提供两种常用的绘图方案,你可以根据习惯选择:

方案1:使用ggplot2包(推荐,语法更直观)

ggplot2是R中最流行的可视化包,能轻松实现分组密度图和垂直线添加:

# 先加载包,未安装的话先运行 install.packages("ggplot2")
library(ggplot2)

# 绘制分组密度图,添加通用垂直线
ggplot(Data, aes(x = IV, color = group, fill = group)) +
  geom_density(alpha = 0.3) +  # alpha设置填充透明度,避免重叠遮挡
  # 这里示例指定垂直线位置为x=50,你可以替换成自己需要的数值
  geom_vline(xintercept = 50, linetype = "dashed", color = "red", size = 1) +
  labs(title = "IV的分组密度图", x = "IV值", y = "密度") +
  theme_minimal()

如果想给每个组添加对应的专属垂直线(比如各组的均值),可以这样写:

# 提前计算两组的IV均值
mean_0 <- mean(Data$IV[Data$group == "0"])
mean_1 <- mean(Data$IV[Data$group == "1"])

ggplot(Data, aes(x = IV, color = group, fill = group)) +
  geom_density(alpha = 0.3) +
  geom_vline(xintercept = mean_0, linetype = "dashed", color = "#F8766D", size = 1) +
  geom_vline(xintercept = mean_1, linetype = "dashed", color = "#00BFC4", size = 1) +
  labs(title = "IV的分组密度图(带组均值垂直线)", x = "IV值", y = "密度") +
  theme_minimal()

方案2:使用基础R绘图

如果你习惯用基础R的原生绘图函数,也可以实现需求:

# 先按group拆分数据
data_0 <- Data[Data$group == "0", ]
data_1 <- Data[Data$group == "1", ]

# 绘制第一组密度曲线,再叠加第二组
plot(density(data_0$IV), col = "red", main = "IV的分组密度图", xlab = "IV值", ylab = "密度")
lines(density(data_1$IV), col = "blue")
# 添加垂直线,示例位置x=50
abline(v = 50, lty = 2, col = "black", lwd = 1)
# 添加图例区分组别
legend("topright", legend = c("group=0", "group=1"), col = c("red", "blue"), lty = 1)

同样,要添加各组均值垂直线的话:

mean_0 <- mean(data_0$IV)
mean_1 <- mean(data_1$IV)

plot(density(data_0$IV), col = "red", main = "IV的分组密度图(带组均值垂直线)", xlab = "IV值", ylab = "密度")
lines(density(data_1$IV), col = "blue")
abline(v = mean_0, lty = 2, col = "red", lwd = 1)
abline(v = mean_1, lty = 2, col = "blue", lwd = 1)
# 补充图例说明垂直线含义
legend("topright", legend = c("group=0", "group=1", "group0均值", "group1均值"), 
       col = c("red", "blue", "red", "blue"), lty = c(1,1,2,2))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:31:56