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

Viewed 19324

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!

4 Answers

A simpler way is to use ggplot and have the variable that you want to plot as a factor. 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. This gives you a nice plot with the legend.

enter image description here

Related