R/plot.retention.R

Defines functions plot.retention

Documented in plot.retention

plot.retention <- function(
  x,                # <retention> object. Could be generated by e.g. mixpanelGetRetention.
  type="all",       # Vector of plots to be shown. Valid values are:
                    # "cohortsByDate", "cohortsByAge", "byDuration".
  percentages=TRUE, # Output as counts or percentages? Default TRUE.
  omitLast=TRUE,    # Omit last value per series? Useful for Mixpanel data, because last
  # value is usually based on partial data!
  colors,           # Colors. Optional.
  durations,        # Selected Durations (index). Default is c(1, 2, 5, 10).
  y,                # Unused.
  ...               # Unused.
) {
  if(percentages) 
    d = x$retainPerc
  else 
    d = x$retainCount
  
  nCohorts = nrow(d)
  nPeriods = ncol(d) - ifelse(omitLast, 1, 0)
  
  if(missing(colors))
    colors = 1:nPeriods
  
  if (any(c("cohortsByDate", "all") %in% type)) {
    ## Case 1: one retention line per cohort; x axis shows Calendar Date.
    plot(c(1, nPeriods), range(d, na.rm=T), type="n", 
         xlab="Calendar Date", ylab="", axes=F)
    axis(1, 1:nPeriods, x$dates[1:nPeriods]); axis(2); axis(4)
    title("Retention Rates of Multiple Cohorts")
    for (i in 1:nCohorts) {
      len = nPeriods - (i - 1)
      lines(i:nPeriods, d[i, 1:len], col=colors[i])
    }
  }
  
  if (any(c("cohortsByAge", "all") %in% type)) {
    ## Case 2: one retention line per cohort; x axis synchronizes cohort start dates.
    plot(c(1, nPeriods), range(d, na.rm=T), type="n", 
         xlab="Periods since Cohort Start", ylab="", axes=F)
    axis(1, 1:nPeriods, colnames(d)[1:nPeriods]); axis(2); axis(4)
    title("Retention Rates of Multiple Cohorts")
    for (i in 1:nCohorts) {
      len = nPeriods - (i - 1)
      lines(1:len, d[i, 1:len], col=colors[i])
    }
  }
  
  ## Case 3: one retention line per selected duration.
  if (any(c("byDuration", "all") %in% type)) {
    if(missing(durations))
      durations = c(1, 2, 5, 10)
    nDurations = length(durations)
    
    plot(c(1, nPeriods), range(d, na.rm=T), type="n", 
         xlab="Calendar Date", ylab="", axes=F)
    axis(1, 1:nPeriods, x$dates[1:nPeriods]); axis(2); axis(4)
    title("Retention for Different Durations")
    for (i in 1:nDurations) {
      len = nPeriods - (i - 1)
      lines(1:len, d[1:len, i], col=colors[i])
    }
    legend("left", legend=colnames(d)[durations], 
           lty=rep(1, nDurations), col=colors[1:nDurations], bty="n")
  }
}

Try the RMixpanel package in your browser

Any scripts or data that you put into this service are public.

RMixpanel documentation built on May 1, 2019, 10:46 p.m.