【问题标题】:plotting CDF plots for various arrays in a data frame为数据框中的各种数组绘制 CDF 图
【发布时间】:2023-03-25 23:27:01
【问题描述】:

我可以使用

绘制 3 个数据系列的累积分布图
library(ggplot2)

a1 <- rnorm(1000, 0, 3)
a2 <- rnorm(1000, 1, 4)
a3 <- rnorm(800, 2, 3)

    df <- data.frame(x = c(a1, a2, a3), ggg=factor(rep(1:3, c(1000,1000,800))))
    ggplot(df, aes(x, colour = ggg)) + 
      stat_ecdf()+
      scale_colour_hue(name="my legend", labels=c('AAA','BBB', 'CCC'))

但是现在我有大约 100 个观察到的数据,例如 a1,a2 ......a100 有 5000 行,我想要累积分布图,但我不想使用循环,而是想使用 apply 或tapply 和 ggplot 包。

**sample data :df = data.frame(matrix(rnorm(20), nrow=5000,ncol=100)).**

【问题讨论】:

    标签: r ggplot2 cdf


    【解决方案1】:

    您可以尝试使用ls mget 组合,例如

    a1 <- rnorm(1000, 0, 3)
    a2 <- rnorm(1000, 1, 4)
    a3 <- rnorm(800, 2, 3)
    a100 <- rnorm(800, 2, 3) # <- adding some more vectors
    a200 <- rnorm(800, 2, 3) # <- adding some more vectors 
    a300 <- rnorm(800, 2, 3) # <- adding some more vectors 
    a1000 <- rnorm(800, 2, 3) # <- adding some more vectors
    
    temp <- mget(ls(pattern = "^a\\d+$"))
    df <- data.frame(x = unlist(temp), ggg = factor(rep(seq_len(length(temp)), sapply(temp, length))))
    ggplot(df, aes(x, colour = ggg)) + 
      stat_ecdf()+
      scale_colour_hue(name="my legend", labels=names(temp))
    


    编辑:根据您的新问题,在您的df 上试试这个(在提供的df 上看起来不太好,因为所有列中的所有值都相等)

    library(reshape2)
    df2 <- melt(df)
    df2$x <- rep(seq_len(nrow(df)), ncol(df))
    ggplot(df2, aes(x, value, color = variable)) + 
      stat_ecdf()+
      scale_colour_hue(name="my legend", labels=names(df))
    

    【讨论】:

    • 嘿@David 非常感谢你能解释一下你代码中的 temp
    • mget 正在使用正则表达式从ls 中指定的全局环境中提取所有数据帧。如果您不知道正则表达式,请尝试在控制台中输入?regex。这种表达方式非常基础。它在数据帧名称的开头搜索“a”,然后确保后面有数字,$ 确保在这些数字之后没有任何内容。我做这些限制是为了避免全局环境中的其他对象也被mget 拉取。
    • 我的变量在数据框名称中为 V1,V2 .... V100 且数据框名称为“dd”我附加了数据框,然后尝试了该功能,但我得到以下错误:不知道如何为动物园类型的对象自动选择比例。默认为连续错误:美学长度必须为 1,或与 dataProblems:ggg 的长度相同
    • 这将是另一个问题。您将不得不使用来自reshape2 包的melt
    • 上面的图不适用于数据框,它只生成一个图,而不是为数据框中的每个变量生成 100 条不同的曲线
    最近更新 更多