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

在R语言中绘制带变量标签图例的联合密度分布图

生成带标签的暴露变量数据集并绘制联合密度分布图

1. 生成带标签的数据集

原代码中用到的label()函数来自Hmisc包,需先加载该包才能正常运行,完整代码如下:

# 加载依赖包
library(Hmisc)

set.seed(42)
n=1000
db = data.frame(id=1:n,
                exp_1 = as.numeric(rnorm(n)),
                exp_2 = as.numeric(rnorm(n)),
                exp_3 = as.numeric(rnorm(n)), 
                exp_4=as.numeric(rnorm(n)))
# 为变量设置自定义标签
label(db$exp_1)="Myx"
label(db$exp_2)="ff3"
label(db$exp_3)="poison-untitled"
label(db$exp_4)="NH3"

2. 绘制联合密度分布图

使用ggplot2包可以快速生成与示例样式一致的联合密度图,核心是将宽格式数据转为长格式,再映射变量标签作为图例名称,完整代码如下:

library(ggplot2)
library(tidyr)

# 将宽格式数据转为长格式,同时关联变量标签
db_long <- db %>%
  select(-id) %>%
  pivot_longer(cols = everything(), names_to = "variable", values_to = "value") %>%
  mutate(label = case_when(
    variable == "exp_1" ~ label(db$exp_1),
    variable == "exp_2" ~ label(db$exp_2),
    variable == "exp_3" ~ label(db$exp_3),
    variable == "exp_4" ~ label(db$exp_4)
  ))

# 绘制叠加密度曲线
ggplot(db_long, aes(x = value, color = label)) +
  geom_density(linewidth = 1) +
  labs(x = "变量值", y = "密度", color = "暴露变量") +
  theme_bw() +
  theme(legend.position = "right")

运行后会生成四条叠加的密度曲线,图例将直接显示你设置的自定义变量标签,样式与目标示例一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:50:25