gpt4 book ai didi

r - 使用 ggplot2 在同一图上的 ECDF

转载 作者:行者123 更新时间:2023-12-03 20:11:39 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Easier way to plot the cumulative frequency distribution in ggplot?

(3 个回答)


3年前关闭。




我有一个数据框,在应用了melt函数后看起来类似于:

 var       val
1 a 0.6133426
2 a 0.9736237
3 b 0.6201497
4 b 0.3482745
5 c 0.3693730
6 c 0.3564962

………………

初始数据框有 3 列,其中包含列名 a、b、c 及其关联值。
我需要在同一张图上绘图,使用 ggplot 为这些列中的每一列(ecdf(a)、ecdf(b)、ecdf(c))使用关联的 ecdf,但我没有这样做。我试过:
p<-ggplot(melt_exp,aes(melt_exp$val,ecdf,colour=melt_exp$var))
pg<-p+geom_step()

但是我收到一个错误:参数意味着不同的行数:34415, 0。

有没有人知道如何做到这一点?该图应该与 plot(ecdf(x)) 返回的图相似,而不是阶梯式的。

谢谢!

最佳答案

我的第一个想法是尝试使用 stat_function ,但由于 ecdf返回一个函数,我无法快速运行。相反,这里有一个解决方案,要求您首先将计算值附加到数据框(使用 Ramnath 的示例数据):

library(plyr) # function ddply()
mydf_m <- ddply(mydf_m, .(variable), transform, ecd = ecdf(value)(value))

ggplot(mydf_m,aes(x = value, y = ecd)) +
geom_line(aes(group = variable, colour = variable))

enter image description here

如果您想对 ECDF 进行平滑估计,您还可以使用 geom_smooth连同函数 ns()来自 spline包裹:
library(splines) # function ns()
ggplot(mydf_m, aes(x = value, y = ecd, group = variable, colour = variable)) +
geom_smooth(se = FALSE, formula = y ~ ns(x, 3), method = "lm")

enter image description here

如上面的评论中所述,从 0.9.2.1 版本开始,ggplot2 具有用于此目的的特定统计信息: stat_ecdf .使用它,我们会做这样的事情:
ggplot(mydf_m,aes(x = value)) + stat_ecdf(aes(colour = variable))

关于r - 使用 ggplot2 在同一图上的 ECDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6989015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com