How to plot multiple ECDF's on one plot in different colors in R

拜拜、爱过 提交于 2019-12-21 18:32:53

问题


I am trying to plot 4 ecdf functions on one plot but can't seem to figure out the proper syntax.

If I have 4 functions "A, B, C, D" what would be the proper syntax in R to get them to be plotted on the same chart with different colors. Thanks!


回答1:


The package latticeExtra provides the function ecdfplot.

library(lattice)
library(latticeExtra)

set.seed(42)
vals <- data.frame(r1=rnorm(100)*0.5,
                   r2=rnorm(100),
                   r3=rnorm(100)*2)

ecdfplot(~ r1 + r2 + r3, data=vals, auto.key=list(space='right')




回答2:


Here is one way (for three of them, works for four the same way):

set.seed(42)
ecdf1 <- ecdf(rnorm(100)*0.5)
ecdf2 <- ecdf(rnorm(100)*1.0)
ecdf3 <- ecdf(rnorm(100)*2.0)
plot(ecdf3, verticals=TRUE, do.points=FALSE)
plot(ecdf2, verticals=TRUE, do.points=FALSE, add=TRUE, col='brown')
plot(ecdf1, verticals=TRUE, do.points=FALSE, add=TRUE, col='orange')

Note that I am using the fact that the third has the widest range, and use that to initialize the canvas. Else you need ylim=c(...).




回答3:


Here is an approach using ggplot2 (using the ecdf objects from [Dirk's answer])(https://stackoverflow.com/a/20601807/1385941)

library(ggplot2)
# create a data set containing the range you wish to use
d <- data.frame(x = c(-6,6))
# create a list of calls to `stat_function` with the colours you wish to use

ll <- Map(f  = stat_function, colour = c('red', 'green', 'blue'),
          fun = list(ecdf1, ecdf2, ecdf3), geom = 'step')


ggplot(data = d, aes(x = x)) + ll



来源:https://stackoverflow.com/questions/20601642/how-to-plot-multiple-ecdfs-on-one-plot-in-different-colors-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!