trajRibbonPlot.R 10.5 KB
Newer Older
dmattek's avatar
dmattek committed
1 2 3 4 5 6 7
#
# Time Course Inspector: Shiny app for plotting time series data
# Author: Maciej Dobrzynski
#
# This module is for plotting group averages as ribbon plots (mean + 95%CI)
#

dmattek's avatar
dmattek committed
8 9 10 11 12 13 14

modTrajRibbonPlotUI =  function(id, label = "Plot Individual Time Series") {
  ns <- NS(id)
  
  tagList(
    fluidRow(
      column(
dmattek's avatar
dmattek committed
15 16
        3,
        radioButtons(ns('rBlegendPos'), 'Legend', list('top' = 'top', 'right' = 'right')),
17
        checkboxInput(ns('chBplotTrajInt'), 'Interactive Plot'),
dmattek's avatar
dmattek committed
18 19
        actionButton(ns('butPlotTraj'), 'Plot!')
      ),
20 21
      column(
        2,
dmattek's avatar
dmattek committed
22
        radioButtons(ns('rBPlotTrajStat'), 'Display', list('Mean only' = 'Mean',
23 24 25
                                                            'Add 95% CI' = 'CI', 
                                                            'Add SE' = 'SE'))
      ),
dmattek's avatar
dmattek committed
26 27
      column(
        3,
dmattek's avatar
dmattek committed
28
        sliderInput(ns('sliPlotTrajSkip'), 'Plot every n-th point', min = 1, max = 10, value = 1, step = 1),
dmattek's avatar
dmattek committed
29
        
dmattek's avatar
dmattek committed
30
        checkboxInput(ns('chBsetXbounds'), 'Bounds for X', FALSE),
dmattek's avatar
dmattek committed
31 32 33 34 35 36 37 38
        fluidRow(
          column(6,
                 uiOutput(ns('uiSetXboundsLow'))
          ),
          column(6,
                 uiOutput(ns('uiSetXboundsHigh'))
          )),
        
dmattek's avatar
dmattek committed
39
        checkboxInput(ns('chBsetYbounds'), 'Bounds for Y', FALSE),
dmattek's avatar
dmattek committed
40 41 42 43 44 45 46
        fluidRow(
          column(6,
                 uiOutput(ns('uiSetYboundsLow'))
          ),
          column(6,
                 uiOutput(ns('uiSetYboundsHigh'))
          ))
dmattek's avatar
dmattek committed
47 48
      ),
      column(
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
49
        2,
dmattek's avatar
dmattek committed
50 51
        numericInput(
          ns('inPlotTrajWidth'),
dmattek's avatar
dmattek committed
52
          'Width [%]',
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
53
          value = PLOTWIDTH,
dmattek's avatar
dmattek committed
54 55 56 57 58 59
          min = 10,
          width = '100px',
          step = 10
        ),
        numericInput(
          ns('inPlotTrajHeight'),
dmattek's avatar
dmattek committed
60
          'Height [px]',
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
61
          value = PLOTRIBBONHEIGHT,
dmattek's avatar
dmattek committed
62 63 64 65 66 67 68 69 70
          min = 100,
          width = '100px',
          step = 50
        )
      )
    ),
    uiOutput(ns('uiPlotTraj')),
    br(),
    modTrackStatsUI(ns('dispTrackStats')),
71
    br(),
dmattek's avatar
dmattek committed
72
    downPlotUI(ns('downPlotTraj'), "Download Plot")
dmattek's avatar
dmattek committed
73 74 75 76
  )
}


77 78
modTrajRibbonPlot = function(input, output, session, 
                             in.data, 
79
                             in.data.stim,
80 81
                             in.facet = 'group', 
                             in.facet.color = NULL, 
82
                             in.fname) {
dmattek's avatar
dmattek committed
83 84 85
  
  ns <- session$ns
  
dmattek's avatar
dmattek committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  
  # UI for bounding the x-axis ====
  output$uiSetXboundsLow = renderUI({
    ns <- session$ns
    
    if(input$chBsetXbounds) {
      
      loc.dt = in.data()
      
      if (is.null(loc.dt)) {
        cat(file = stderr(), 'uiSetXboundsLow: dt is NULL\n')
        return(NULL)
      }
      
      numericInput(
        ns('inSetXboundsLow'),
        label = 'Lower',
        step = 0.1, 
        value = floor(min(loc.dt[[COLRT]], na.rm = T))
      )
    }
  })
  
  
  output$uiSetXboundsHigh = renderUI({
    ns <- session$ns
    
    if(input$chBsetXbounds) {
      
      loc.dt = in.data()
      
      if (is.null(loc.dt)) {
        cat(file = stderr(), 'uiSetXboundsHigh: dt is NULL\n')
        return(NULL)
      }
      
      numericInput(
        ns('inSetXboundsHigh'),
        label = 'Upper',
        step = 0.1, 
        value = ceil(max(loc.dt[[COLRT]], na.rm = T))
      )
    }
  })
  
  
  # UI for bounding the y-axis ====
  output$uiSetYboundsLow = renderUI({
    ns <- session$ns
    
    if(input$chBsetYbounds) {
      
      loc.dt = in.data()
      
      if (is.null(loc.dt)) {
        cat(file = stderr(), 'uiSetYboundsLow: dt is NULL\n')
        return(NULL)
      }
      
      numericInput(
        ns('inSetYboundsLow'),
        label = 'Lower',
        step = 0.1, 
dmattek's avatar
dmattek committed
149
        value = min(loc.dt[[COLY]], na.rm = T)
dmattek's avatar
dmattek committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
      )
    }
  })
  
  
  output$uiSetYboundsHigh = renderUI({
    ns <- session$ns
    
    if(input$chBsetYbounds) {
      
      loc.dt = in.data()
      
      if (is.null(loc.dt)) {
        cat(file = stderr(), 'uiSetYboundsHigh: dt is NULL\n')
        return(NULL)
      }
      
      numericInput(
        ns('inSetYboundsHigh'),
        label = 'Upper',
        step = 0.1, 
dmattek's avatar
dmattek committed
171
        value = max(loc.dt[[COLY]], na.rm = T)
dmattek's avatar
dmattek committed
172 173 174 175 176 177
      )
    }
  })
  
  # Plotting ====
  
dmattek's avatar
dmattek committed
178 179
  output$uiPlotTraj = renderUI({
    if (input$chBplotTrajInt)
180 181 182 183 184
       plotlyOutput(
       ns("outPlotTrajInt"),
       width = paste0(input$inPlotTrajWidth, '%'),
       height = paste0(input$inPlotTrajHeight, 'px')
    ) else
dmattek's avatar
dmattek committed
185 186 187 188 189 190 191 192 193
        plotOutput(
          ns("outPlotTraj"),
          width = paste0(input$inPlotTrajWidth, '%'),
          height = paste0(input$inPlotTrajHeight, 'px')
        )
  })
  
  
  callModule(modTrackStats, 'dispTrackStats',
dmattek's avatar
dmattek committed
194 195
             in.data = in.data,
             in.bycols = in.facet)
dmattek's avatar
dmattek committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  
  
  output$outPlotTraj <- renderPlot({
    
    loc.p = plotTraj()
    if(is.null(loc.p))
      return(NULL)
    
    return(loc.p)
  })
  
  
  output$outPlotTrajInt <- renderPlotly({
    # This is required to avoid
    # "Warning: Error in <Anonymous>: cannot open file 'Rplots.pdf'"
    # When running on a server. Based on:
    # https://github.com/ropensci/plotly/issues/494
    if (names(dev.cur()) != "null device")
      dev.off()
    pdf(NULL)
    
    loc.p = plotTraj()
    if(is.null(loc.p))
      return(NULL)
    
    return(plotly_build(loc.p))
  })
  
  
  
  # Trajectory plot - download pdf
227 228 229
  callModule(downPlot, "downPlotTraj", 
             in.fname = in.fname, 
             plotTraj, TRUE)
dmattek's avatar
dmattek committed
230 231
  
  plotTraj <- function() {
232
    cat(file = stderr(), 'plotTrajRibbon: in\n')
dmattek's avatar
dmattek committed
233 234
    locBut = input$butPlotTraj
    
235 236 237
    # Check if main data exists
    # Thanks to solate all mods in the left panel are delayed 
    # until clicking the Plot button
dmattek's avatar
dmattek committed
238
    loc.dt = isolate(in.data())
239 240 241
    validate(
      need(!is.null(loc.dt), "Nothing to plot. Load data first!")
    )    
dmattek's avatar
dmattek committed
242
    
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    cat(file = stderr(), 'plotTrajRibbon: dt not NULL\n')
    
    # check if stim data exists
    loc.dt.stim = isolate(in.data.stim())
    
    if (is.null(loc.dt.stim)) {
      cat(file = stderr(), 'plotTrajRibbon: stim is NULL\n')
    } else {
      cat(file = stderr(), 'plotTrajRibbon: stim not NULL\n')
      
      # choose only 1st group of stimulation pattern for ribbon plot
      
      loc.groups = unique(loc.dt.stim[['group']])
      if(length(loc.groups) > 1) {
        cat(file = stderr(), 'plotTrajRibbon: more than 1 group in stim; choosing 1st\n')
        loc.dt.stim = loc.dt.stim[group == loc.groups[1]]
      }
    }
    
dmattek's avatar
dmattek committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    
    
    # Future: change such that a column with colouring status is chosen by the user
    # colour trajectories, if dataset contains mid.in column
    # with filtering status of trajectory
    if (sum(names(loc.dt) %in% 'mid.in') > 0)
      loc.line.col.arg = 'mid.in'
    else
      loc.line.col.arg = NULL
    
    # select every other point for plotting
    loc.dt = loc.dt[, .SD[seq(1, .N, input$sliPlotTrajSkip)], by = id]
    
    # check if columns with XY positions are present
    if (sum(names(loc.dt) %like% 'pos') == 2)
      locPos = TRUE
    else
      locPos = FALSE
    
    # check if column with ObjectNumber is present
    if (sum(names(loc.dt) %like% 'obj.num') == 1)
      locObjNum = TRUE
    else
      locObjNum = FALSE
    
    
    
    # If in.facet.color present,
    # make sure to include the same number of colours in the palette,
    # as the number of groups in dt.
    # in.facet.color is typically used when plotting time series within clusters.
    # Then, the number of colours in the palette has to be equal to the number of clusters (facetted according to in.facet variable).
    # This might differ if the user selects manually clusters to display.
    if (is.null(in.facet.color)) 
      loc.facet.col = NULL 
    else {
      # get group numbers in dt; 
      # loc.dt[, c(in.facet), with = FALSE] returns a data table with a single column
      # [[1]] at the end extracts the first column and returns as a vector
      loc.groups = unique(loc.dt[, c(in.facet), with = FALSE][[1]])
      
      # get colour palette
      # the length is equal to the number of groups in the original dt.
      # When plotting time series within clusters, the length equals the number of clusters.
      loc.facet.col = in.facet.color()$cl.col
      loc.facet.col = loc.facet.col[loc.groups]
    }
    
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    
    # aggregate data; calculate Mean, CI or SE
    loc.ribbon.lohi = NULL
    
    if(input$rBPlotTrajStat == "Mean") {
      # calculate the mean
      loc.dt.aggr = loc.dt[, .(Mean = mean(get(COLY))), by = c(in.facet, COLRT)]
      
    } else if(input$rBPlotTrajStat == "CI") {
      # calculate the mean and the confidence intervals
      loc.dt.aggr = LOCcalcTrajCI(in.dt = loc.dt, 
                                  in.col.meas = COLY, 
                                  in.col.by = c(in.facet, COLRT), 
                                  in.type = 'normal')
      
      loc.ribbon.lohi = c('Lower', 'Upper')
      
    } else if(input$rBPlotTrajStat == "SE") {
      # calculate the mean and the standard error of the mean
      loc.dt.aggr = loc.dt[, .(Mean = mean(get(COLY)),
                               Lower = mean(get(COLY)) - LOCstderr(get(COLY)),
                               Upper = mean(get(COLY)) + LOCstderr(get(COLY))), by = c(in.facet, COLRT)]
      
      loc.ribbon.lohi = c('Lower', 'Upper')
    }
    
    
    
    # set the grouing column to a factor (for plotting)
dmattek's avatar
dmattek committed
339 340
    loc.dt.aggr[, (in.facet) := as.factor(get(in.facet))]

341
    # setting bounds for displaying of x and y axes
dmattek's avatar
dmattek committed
342 343 344 345 346 347 348 349 350
    loc.xlim.arg = NULL
    if(input$chBsetXbounds) {
      loc.xlim.arg = c(input$inSetXboundsLow, input$inSetXboundsHigh)
    } 
    
    loc.ylim.arg = NULL
    if(input$chBsetYbounds) {
      loc.ylim.arg = c(input$inSetYboundsLow, input$inSetYboundsHigh)
    } 
dmattek's avatar
dmattek committed
351
    
352
    p.out = LOCplotTrajRibbon(dt.arg = loc.dt.aggr, 
353
                           x.arg = COLRT, 
dmattek's avatar
dmattek committed
354 355 356
                           y.arg = 'Mean',
                           col.arg = loc.facet.col,
                           group.arg = in.facet,
357 358
                           dt.stim.arg = loc.dt.stim,
                           x.stim.arg = c('tstart', 'tend'),
359 360
                           y.stim.arg = c('ystart', 'yend'), 
                           ribbon.lohi.arg = loc.ribbon.lohi,
dmattek's avatar
dmattek committed
361 362
                           xlim.arg = loc.xlim.arg,
                           ylim.arg = loc.ylim.arg,
363
                           xlab.arg = 'Time',
364
                           ylab.arg = '') +
365 366 367 368 369
      LOCggplotTheme(in.font.base = PLOTFONTBASE, 
                     in.font.axis.text = PLOTFONTAXISTEXT, 
                     in.font.axis.title = PLOTFONTAXISTITLE, 
                     in.font.strip = PLOTFONTFACETSTRIP, 
                     in.font.legend = PLOTFONTLEGEND) + 
370
      theme(legend.position = input$rBlegendPos)
dmattek's avatar
dmattek committed
371 372 373 374
    
    return(p.out)
  }
}