Creating a cumulative step graph in R

北城以北 提交于 2019-12-01 05:40:29
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)

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

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

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