如何在R中以不同颜色绘制多个ECDF

时间:2013-12-16 00:22:31

标签: r plot ecdf

我试图在一个图上绘制4个ecdf函数,但似乎无法弄清楚正确的语法。

如果我有4个函数“A,B,C,D”,那么R中的正确语法是将它们绘制在具有不同颜色的相同图表上。谢谢!

4 个答案:

答案 0 :(得分:8)

这是一种方式(对于其中三种,以相同的方式工作四种方式):

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

请注意,我使用的是第三个具有最宽范围的事实,并使用它来初始化画布。否则,您需要ylim=c(...)

enter image description here

答案 1 :(得分:6)

latticeExtra提供函数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')

ecdfplot with legend

答案 2 :(得分:2)

这是一种使用ggplot2的方法(使用[Dirk的答案]中的ecdf对象)(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

enter image description here

答案 3 :(得分:0)

更简单的方法是使用 ggplot 并将要绘制的变量作为因子。在下面的示例中,我将投资组合作为一个因素,并按投资组合绘制利率分布图。

# select a palette
myPal <- c( 'royalblue4', 'lightsteelblue1', 'sienna1')

# plot the Interest Rate distribution of each portfolio
# make an ecdf of each category in Portfolio which is a factor
g2 <- ggplot(mortgage, aes(x = Interest_Rate, color = Portfolio)) + 
      scale_color_manual(values = myPal) +
      stat_ecdf(lwd = 1.25, geom = "line")
      
g2

您还可以在geom = "step", geom = "point"函数中设置lwd和调整线宽stat_ecdf()。这为您提供了一个很好的图例情节。

enter image description here

相关问题