5

我想在同一张图中绘制多个变量的 CDF 图。变量的长度不同。为了简化细节,我使用以下示例代码:

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 = gl(3, 1000))
ggplot(df, aes(x, colour = ggg)) + stat_ecdf()+ coord_cartesian(xlim = c(0, 3)) + scale_colour_hue(name="my legend", labels=c('AAA','BBB', 'CCC'))

我们可以看到,a3 的长度是 800,与 a1、a2 不同。当我运行代码时,它显示:

> df <- data.frame(x = c(a1, a2, a3),ggg = gl(3, 1000))
Error in data.frame(x = c(a1, a2, a3), ggg = gl(3, 1000)) : 
arguments imply differing number of rows: 2800, 3000
> ggplot(df, aes(x, colour = ggg)) + stat_ecdf()+ coord_cartesian(xlim = c(0, 3)) +    scale_colour_hue(name="my legend", labels=c('AAA','BBB', 'CCC'))
Error: ggplot2 doesn't know how to deal with data of class function

那么,如何使用 ggplot2 在同一图中绘制不同长度的不同变量的 cdf 图?期待帮助!

4

2 回答 2

4

ggplot处理每组中的不同计数完全没有问题。问题在于您创建了因子 ggg。用这个:

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'))

此外,您设置它的方式,设置xlim=c(0,3),在 上绘制 cdf [0,3],正如您在上图中看到的那样,它或多或少是一条直线。

于 2014-05-18T00:15:57.263 回答
3

你在那个 ggplot 中是对的,确实似乎确实希望每组中的计数数量相等。因此stat_ecdf,也许您可​​以自己进行计算,而不是使用

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))))

df <- df[order(df$x), ]
df$ecdf <- ave(df$x, df$ggg, FUN=function(x) seq_along(x)/length(x))

ggplot(df, aes(x, ecdf, colour = ggg)) + geom_line() + scale_colour_hue(name="my legend", labels=c('AAA','BBB', 'CCC'))

请注意,您使用gl()不正确;您的代码假设所有三个组也有 1000 个条目。在这里,我将其更改rep()为每组获得正确数量的标签。

ecdf pggplot

于 2014-05-17T19:16:08.680 回答