ggplot单个密度与平均密度

时间:2014-09-17 11:05:06

标签: r ggplot2

我想将两个不同类别的密度绘制为线,然后每个类别的平均密度将覆盖为alpha 。以下代码显示' mean'密度只对疾病和治疗进行了总结。我怎样才能用代表每个人密度的线来覆盖它(最好是疾病的红色= 1,疾病的蓝色= 2)?即每个疾病的一条线,该例中的治疗组合:

# Initialise data frame in melted form
    # 2 disease categories
    # 10 people from each disease
    # 2 treatments given to each individual
    # 25 variables with measured values per person/treatment combination
set.seed(6737334)
df <- data.frame(id = 1:(2*10*2*25), var = rep(1:25, times=2*10), 
                 val = rnorm(2*10*2*25),
                 disease = as.factor(rep(1:2, each=2*10*25)),
                 treat = as.factor(rep(1:2, times=10, each=25)))

plot <- ggplot(df, aes(x=val, fill=disease)) + geom_density(alpha=.3) +
    facet_grid(treat ~ .)

print(plot)

Image of ggplot produced by the above code

##################编辑

此代码非常接近我想要的解决方案。如何使当前黑色的线条与疾病类别的颜色相匹配?

# Initialise data frame in melted form
    # 2 disease categories
    # 10 people from each disease
    # 2 treatments given to each individual
    # 25 variables with measured values per person/treatment combination
set.seed(6737334)
df <- data.frame(id = 1:(2*10*2*25), var = rep(1:25, times=2*10),
                 test = as.factor(rep(1:(2*10), each=25)),
                 val = rnorm(2*10*2*25),
                 disease = as.factor(rep(1:2, each=2*10*25)),
                 treat = as.factor(rep(1:2, times=10, each=25)))

ggplot(df) + 
    geom_density(aes(x=val, group=test, color=disease)) +
    geom_density(aes(x=val, fill=disease), color=NA, alpha=.5) +
    facet_grid(treat ~ .)

enter image description here

2 个答案:

答案 0 :(得分:2)

如果我理解你的问题,这可能是你正在寻找的:

ggplot(df) + 
  geom_density(aes(x=val, color=disease)) +
  geom_density(aes(x=val), color=NA, fill="grey", alpha=.5) +
  facet_grid(treat ~ .) +
  theme_bw()

给出: enter image description here

答案 1 :(得分:1)

该方法原来是使用group aes()选项interaction。见下面的完整示例。感谢上面的@Jaap和this question指向正确的方向。

# Initialise data frame in melted form
    # 2 disease categories
    # 10 people from each disease
    # 2 treatments given to each individual
    # 25 variables with measured values per person/treatment combination
set.seed(6737334)
df <- data.frame(id = 1:(2*10*2*25), var = rep(1:25, times=2*10),
                 test = as.factor(rep(1:(2*10), each=25)),
                 val = rnorm(2*10*2*25),
                 disease = as.factor(rep(1:2, each=2*10*25)),
                 treat = as.factor(rep(1:2, times=10, each=25)))

ggplot(df) + 
    geom_density(aes(x=val, group=interaction(test,disease), colour=disease)) +
    geom_density(aes(x=val, fill=disease), alpha=.5) +
    guides(fill=guide_legend(title="mean")) +     # else legend title 'NA'
    facet_grid(treat ~ .)

enter image description here