【问题标题】:Plotting a distribution densities for two classes in R在 R 中绘制两个类别的分布密度
【发布时间】:2017-11-02 08:49:49
【问题描述】:

我有两个类(死的和活的)的数据库,我想为每个类的特定特征绘制分布图。

像这样:

你能帮忙吗?

可重现的数据集:

输入(数据[1:100,])

structure(list(`dead` = structure(c(1L, 1L, 1L, 
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L), .Label = c("no", "yes"), class = "factor"), `Magnesium` = c(2.17, 
2.31, 2.14, 2.28, 2.17, 1.83, 1.9, 1.94, 2.68, 1.66, 2.14, 2.64, 
2.41, 2.19, 1.46, 2.34, 1.57, 2.52, 1.97, 1.8, 2.36, 1.6, 2.02, 
2.07, 1.44, 2.09, 2.08, 2.02, 2.52, 1.87, 2.72, 2.52, 1.58, 2.52, 
1.75, 2.81, 2, 1.83, 3.35, 1.74, 2.19, 2.44, 1.91, 2.33, 2.23, 
2.03, 2.13, 2.19, 2.02, 1.96, 2.52, 2.77, 2.17, 1.67, 2.04, 2.32, 
1.34, 1.75, 2.07, 2.23, 1.78, 2.69, 2.02, 3.1, 2.18, 1.61, 2.2, 
2.02, 2.3, 2, 2.45, 2.13, 1.96, 1.98, 2.1, 3.38, 1.36, 2.04, 
1.52, 3.12, 2.07, 2.68, 2.18, 2.59, 2.07, 1.77, 2.02, 2.31, 2.23, 
3.79, 1.41, 2.3, 1.97, 1.84, 1.95, 2.43, 2.17, 1.79, 1.7, 2.18
)), .Names = c("dead", "Magnesium"
), row.names = c(NA, 100L), class = "data.frame")

【问题讨论】:

  • 如果您向我们提供可重现的数据集和您迄今为止尝试过的一些代码,将会很有帮助。
  • @Adam Quek 我不知道如何开始创建它,所以我没有代码,但我添加了一个可重现的数据集我有一个不平衡的问题,所以不是很多是的)

标签: r plot distribution stat


【解决方案1】:
d_list <- split(dat, dat$dead)
d_list <- lapply(d_list, function(x)density(x[, "Magnesium"])[c("x", "y")])
d_list <- lapply(d_list, function(x) do.call(data.frame, x))

plot(d_list[[1]], type="n", xlab="Magnesium", ylab="Density", main="Magnesium Level of two classes of patients")
for(i in seq(length(d_list))) lines(d_list[[i]], col=c("black", "red")[i], lty=i)
legend("topright", names(d_list), lty=1:2, col=c("black", "red"))

当然,ggplot 会更容易:

ggplot(dat, aes(Magnesium, col=dead, fill=dead)) + 
    geom_density(alpha=.5) 

【讨论】:

    【解决方案2】:

    使用ggplot2(假设df 是您的数据框):

    library(ggplot2)
    ggplot(df) +
        geom_density(aes(x = Magnesium, 
                         group = dead, 
                         color = dead, 
                         fill = dead), 
                     alpha = .2, 
                     size = .25) +
        scale_fill_discrete('', labels = c('Alive', 'Dead')) +
        scale_color_discrete('', labels = c('Alive', 'Dead')) +
        scale_x_continuous(limits = c(0, NA)) +
        theme_minimal()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 2015-10-10
      • 2017-02-18
      相关资源
      最近更新 更多