Creating a cumulative step graph in R

前端 未结 3 1512
有刺的猬
有刺的猬 2020-12-18 08:34

Say I have this example data frame

set.seed(12345)
n1 <- 3
n2 <- 10
n3 <- 60

times <- seq(0, 100, 0.5)

individual <- c(rep(1, n1), 
                 


        
相关标签:
3条回答
  • 2020-12-18 08:50
    df$step <- 1
    
    library(plyr)
    df <- ddply(df,.(individual),transform,step=cumsum(step))
    
    plot(step~events,data=df[df$individual==1,],type="s",xlim=c(0,max(df$events)),ylim=c(0,max(df$step)),xlab="time",ylab="step")
    lines(step~events,data=df[df$individual==2,],type="s",col=2)
    lines(step~events,data=df[df$individual==3,],type="s",col=3)
    

    step plot

    0 讨论(0)
  • 2020-12-18 08:50

    There is also the stepfun function in the stats package. Using that, you could use the plot method for that object class:

    sdf <- split(df, individual)
    
    plot(1, 1, type = "n", xlim = c(0, max(events)), ylim = c(0, max(table(individual))),
      ylab = "step", xlab = "time")
    
    sfun <- lapply(sdf, function(x){
        sf <- stepfun(sort(x$events), seq_len(nrow(x) + 1) - 1)
        plot(sf, add = TRUE, col = unique(x$individual), do.points = FALSE)
    })
    

    enter image description here

    0 讨论(0)
  • 2020-12-18 08:54

    Use ggplot2:

    library(ggplot2)
    
    # Add step height information with sequence and rle
    df$step <- sequence(rle(df$individual)$lengths)
    
    # plot
    df$individual <- factor(df$individual)
    ggplot(df, aes(x=events, group=individual, colour=individual, y=step)) + 
      geom_step()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题