Search code examples
rgraph

R ethogram or actogram script


I am trying to build an ethogram or actogram figure in R. I already measured a single behavior over 150 seconds (with a 1 sec resolution), in which I wrote down the following in excel: an empty cell represents "no behavior", and cell containing a 1 represents "behavior". Each animal represents one row (150 cells long), and the number of animals scored is different in each experiment (n between 11 and 20). So far, I do have all raw data exported as *.csv

Here's an example of the first four rows containing each ~40 data points from one *.csv file (each row is 1 animal, each data point is comma separated):

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1,1,1,1,1,1,1,1,1,1

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1,1,1,1,1,1,1,1,1,

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1,1,,,,,,1,1,1,,,,

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1,1,,1,1,1,1,1,,,,

I would like to create a graph in R looking similar to the one in Figure 7C shown here: https://elife-publishing-cdn.s3.amazonaws.com/08758/elife-08758-fig7-v2.jpg (the whole, free article is here: https://elifesciences.org/content/4/e08758). The behavior would be plotted as "tiny boxes" over time (coloring could be changed later in illustrator). And it would be nice to create each one graph from one *csv file (experiment).

Who can help me?


Solution

  • Here's a possible solution using image() function :

    # custom function using image to emulate an ethograph
    ethograph <- function(zeroOneMatrix, color='blue',xlab='behaviour',ylab='animals'){
      m <- as.matrix(zeroOneMatrix)
      m[m == 0] <- NA
      nAnimals <- nrow(m)
      nTimeSlots <- ncol(m)
    
      image(x=1:nTimeSlots,
            y=1:nAnimals,
            z=t(m[nAnimals:1,]),
            col=c(color),
            xlab=xlab,
            ylab=ylab,
            yaxt = 'n')
    }
    
    # here we create a random matrix of 0 and 1 (animals on the rows and time slots on columns)
    # of course you will get your data reading the csv
    set.seed(123)
    nTimeSlots <- 150
    nAnimals <- 50
    csv1 <- matrix(sample(0:1,nTimeSlots*nAnimals,replace=TRUE),nrow=nAnimals)
    
    # let's plot
    ethograph(csv1, color='blue')
    

    Result:

    enter image description here