简体   繁体   English

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

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

I am trying to plot 4 ecdf functions on one plot but can't seem to figure out the proper syntax.我试图在一个图上绘制 4 个 ecdf 函数,但似乎无法找出正确的语法。

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.如果我有 4 个函数“A、B、C、D”,那么 R 中的正确语法是使它们以不同颜色绘制在同一个图表上。 Thanks!谢谢!

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(...) .否则你需要ylim=c(...)

在此处输入图片说明

The package latticeExtra provides the function ecdfplot .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

Here is an approach using ggplot2 (using the ecdf objects from [Dirk's answer])( https://stackoverflow.com/a/20601807/1385941 )这是使用ggplot2的方法(使用 [Dirk's answer] 中的 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

在此处输入图片说明

A simpler way is to use ggplot and have the variable that you want to plot as a factor.一种更简单的方法是使用 ggplot 并将要绘制的变量作为因子。 In the example below, I have Portfolio as a factor and plotting the distribution of Interest Rates by Portfolio.在下面的示例中,我将投资组合作为一个因素,并按投资组合绘制利率分布图。

# 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

You can also set geom = "step", geom = "point" and adjust the line width lwd in the stat_ecdf() function.您还可以在stat_ecdf()函数中设置geom = "step", geom = "point"并调整线宽lwd This gives you a nice plot with the legend.这为您提供了一个很好的图例情节。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM