【问题标题】:R: overlay density plot with lines based on condition of a columnR:基于列条件的线覆盖密度图
【发布时间】:2021-08-18 19:44:34
【问题描述】:

我有一个数据框,它由一列条件(字符串)和多列数值组成。对于每一列,我想创建一个叠加密度图,其中每条线代表一个条件。我找到了许多解决方案,将每一列作为一条线覆盖在同一个图上,但不是如何通过根据条件分组来创建线。由于这是一个大型数据集,我宁愿不手动指定组。

condition c2 c3 c4
b 1 0 2
c 3 1 2
a 5 0 1
a 2 4 3
c 1 1 1
b 2 3 3
a 1 0 2
c 3 1 2
c 6 0 2
a 2 0 1
c 1 3 1
b 4 3 0

使用此示例数据,我想为 2-4 列中的每一列绘制一个密度图。每个图应该有 3 行(代表 a、b 和 c)。

我最好用 ggplot 来做这个。

【问题讨论】:

    标签: r ggplot2 density-plot


    【解决方案1】:

    另一个选项是ggdensity

    library(ggpubr)
    out <- ggdensity(df, x = c("c2", "c3", "c4"), color = "condition",
             fill = "condition")
    ggarrange(plotlist = out, ncol = 2, nrow = 2)
    

    -输出

    数据

    df <- structure(list(condition = c("b", "c", "a", "a", "c", "b", "a", 
    "c", "c", "a", "c", "b"), c2 = c(1L, 3L, 5L, 2L, 1L, 2L, 1L, 
    3L, 6L, 2L, 1L, 4L), c3 = c(0L, 1L, 0L, 4L, 1L, 3L, 0L, 1L, 0L, 
    0L, 3L, 3L), c4 = c(2L, 2L, 1L, 3L, 1L, 3L, 2L, 2L, 2L, 1L, 1L, 
    0L)), class = "data.frame", row.names = c(NA, -12L))
    

    【讨论】:

    • 是否有一种简单的方法可以在每个图上叠加另一条线以获得所有 3 个条件的平均密度?
    • @keenan 你需要add = "mean"out &lt;- ggdensity(df, x = c("c2", "c3", "c4"), color = "condition", fill = "condition", add = "mean")
    • 这会为每个条件添加一条水平平均线。我希望有一条线显示整体的平均密度,无论条件如何。所以本质上是在完全不考虑条件的情况下覆盖另一个密度图。
    • @keenan 您能否将其作为新问题发布,因为这可能需要更多修改
    【解决方案2】:
    ggplot(df, aes(x = value, fill = condition)) + 
        geom_density(alpha = 0.5) +
        facet_wrap(~name, scales = "free_x") +
        theme_classic()
    

    【讨论】:

      【解决方案3】:
      library(tidyr)
      library(ggplot2)
      
      df %>% 
        pivot_longer(-condition) %>% 
        ggplot(aes(value, color = condition)) +
        geom_density() + 
        facet_wrap(~ name)
      

      返回

      编辑 感谢 Brenton M. Wiernik 的评论,我们可以使用 scales = "free" 单独缩放所有地块。

      df %>% 
        pivot_longer(-condition) %>% 
        ggplot(aes(value, color = condition)) +
        geom_density(alpha = .3) +
        facet_wrap(~ name, scales = "free")
      

      返回

      【讨论】:

      • 我的正常数据集中的值之间的差异太大,所以我认为我需要单独制作每个图。我是否需要为每个数据框制作不同的更长的数据框?或者有没有一种简单的方法来指定使用哪一列?或者以不同的方式缩放每一个?
      • scales = "free_x" 添加到facet_wrap() 函数到所有要单独缩放的方面(此处为变量)。
      • @Matin Gal 使用 fill 而不是 color
      • 或者同时使用。 ;-)
      猜你喜欢
      • 2014-03-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2016-02-06
      • 2022-06-15
      相关资源
      最近更新 更多