trajPlot.R 7.44 KB
Newer Older
dmattek's avatar
dmattek committed
1 2 3 4 5 6 7 8
#
# Time Course Inspector: Shiny app for plotting time series data
# Author: Maciej Dobrzynski
#
# This is the module for plotting individual time series
#


dmattek's avatar
dmattek committed
9 10
require(DT)

dmattek's avatar
dmattek committed
11 12
# UI ----

dmattek's avatar
Mod:  
dmattek committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
modTrajPlotUI =  function(id, label = "Plot Individual Time Series") {
  ns <- NS(id)
  
  tagList(
    fluidRow(
      column(
        3,
        numericInput(
          ns('inPlotTrajFacetNcol'),
          '#Columns:',
          value = 4,
          min = 1,
          width = '100px',
          step = 1
        ),
        checkboxInput(ns('chBplotTrajInt'), 'Interactive Plot?'),
        actionButton(ns('butPlotTraj'), 'Plot!')
      ),
      column(
        3,
        checkboxGroupInput(ns('chBPlotTrajStat'), 'Stats:', list('Mean' = 'mean', '95% conf. interv.' = 'CI', 'Std. error' = 'SE'))
      ),
      column(
        3,
37
        sliderInput(ns('sliPlotTrajSkip'), 'Plot every n-th point:', min = 1, max = 10, value = 1, step = 1),
38 39 40 41 42 43 44 45 46 47 48
        checkboxInput(ns('chBsetColBounds'), 'Set bounds for y-axis', FALSE),
        
        fluidRow(
          column(6,
                 uiOutput(ns('uiSetColBoundsLow'))
          ),
          column(6,
                 uiOutput(ns('uiSetColBoundsHigh'))
          )
        )
        
dmattek's avatar
Mod:  
dmattek committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
      ),
      column(
        3,
        numericInput(
          ns('inPlotTrajWidth'),
          'Width [%]:',
          value = 100,
          min = 10,
          max = 100,
          width = '100px',
          step = 10
        ),
        numericInput(
          ns('inPlotTrajHeight'),
          'Height [px]:',
          value = 800,
          min = 100,
          width = '100px',
          step = 50
        )
      )
    ),
    uiOutput(ns('uiPlotTraj')),
dmattek's avatar
dmattek committed
72 73 74
    br(),
    modTrackStatsUI(ns('dispTrackStats')),
    
dmattek's avatar
Mod:  
dmattek committed
75 76 77 78
    downPlotUI(ns('downPlotTraj'), "Download PDF")
  )
}

dmattek's avatar
dmattek committed
79
# Server ----
80 81
modTrajPlot = function(input, output, session, 
                       in.data, 
82
                       in.data.stim,
83 84 85
                       in.fname,
                       in.facet = 'group', 
                       in.facet.color = NULL) {
dmattek's avatar
Mod:  
dmattek committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
  
  ns <- session$ns
  
  output$uiPlotTraj = renderUI({
    if (input$chBplotTrajInt)
      plotlyOutput(
        ns("outPlotTrajInt"),
        width = paste0(input$inPlotTrajWidth, '%'),
        height = paste0(input$inPlotTrajHeight, 'px')
      ) else
        plotOutput(
          ns("outPlotTraj"),
          width = paste0(input$inPlotTrajWidth, '%'),
          height = paste0(input$inPlotTrajHeight, 'px')
        )
  })
  
dmattek's avatar
dmattek committed
103

104
  # UI for trimming y-axis
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
  output$uiSetColBoundsLow = renderUI({
    ns <- session$ns
    
    if(input$chBsetColBounds) {
      
      loc.dt = in.data()
      
      numericInput(
        ns('inSetColBoundsLow'),
        label = 'Lower',
        step = 0.1, 
        value = floor(min(loc.dt[['y']], na.rm = T))
      )
    }
  })
  
  
  output$uiSetColBoundsHigh = renderUI({
    ns <- session$ns
    
    if(input$chBsetColBounds) {
      
      loc.dt = in.data()
      
      numericInput(
        ns('inSetColBoundsHigh'),
        label = 'Upper',
        step = 0.1, 
        value = ceil(max(loc.dt[['y']], na.rm = T))
      )
    }
  })

    output$uiSlYTrim = renderUI({
139 140 141 142
    cat(file = stderr(), 'UI uiSlYTrim\n')
    
    loc.dt = in.data()
    
dmattek's avatar
dmattek committed
143 144
      locYmin = signif(min(loc.dt$y, na.rm = T), 4)
      locYmax = signif(max(loc.dt$y, na.rm = T), 4)
145

146 147 148 149 150 151 152 153 154 155 156 157
      sliderInput(
        ns('slYTrim'),
        label = 'Trim y-axis',
        min = locYmin,
        max = locYmax,
        value = c(locYmin, locYmax)
      )
      
  })
  
  
  
dmattek's avatar
dmattek committed
158 159 160 161
  callModule(modTrackStats, 'dispTrackStats',
             in.data = in.data)
  
  
dmattek's avatar
Mod:  
dmattek committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  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)
    
185
    return(ggplotly(loc.p))
dmattek's avatar
Mod:  
dmattek committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
  })
  
  
  
  # Trajectory plot - download pdf
  callModule(downPlot, "downPlotTraj", in.fname, plotTraj, TRUE)
  
  plotTraj <- function() {
    cat(file = stderr(), 'plotTraj: in\n')
    locBut = input$butPlotTraj
    
    if (locBut == 0) {
      cat(file = stderr(), 'plotTraj: Go button not pressed\n')
      
      return(NULL)
    }
    
203
    # check main data exists
dmattek's avatar
Mod:  
dmattek committed
204 205 206 207 208 209 210 211 212
    loc.dt = isolate(in.data())
    
    cat("plotTraj: on to plot\n\n")
    if (is.null(loc.dt)) {
      cat(file = stderr(), 'plotTraj: dt is NULL\n')
      return(NULL)
    }
    
    cat(file = stderr(), 'plotTraj: dt not NULL\n')
213 214 215 216 217 218 219 220 221 222 223


    # check if stim data exists
    loc.dt.stim = isolate(in.data.stim())

    if (is.null(loc.dt.stim)) {
      cat(file = stderr(), 'plotTraj: dt.stim is NULL\n')
    } else {
      cat(file = stderr(), 'plotTraj: dt.stim not NULL\n')
    }

dmattek's avatar
Mod:  
dmattek committed
224 225 226
    
    
    # Future: change such that a column with colouring status is chosen by the user
227
    # colour trajectories, if dataset contains mid.in column
dmattek's avatar
Mod:  
dmattek committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    # 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
    
243 244 245 246 247 248 249 250
    # check if column with ObjectNumber is present
    if (sum(names(loc.dt) %like% 'obj.num') == 1)
      locObjNum = TRUE
    else
      locObjNum = FALSE
    
    
    
dmattek's avatar
Fixed:  
dmattek committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    # 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]
    }
271

dmattek's avatar
Fixed:  
dmattek committed
272
    
273
    p.out = LOCplotTraj(
dmattek's avatar
Mod:  
dmattek committed
274 275 276 277 278 279
      dt.arg = loc.dt,
      x.arg = 'realtime',
      y.arg = 'y',
      group.arg = "id",
      facet.arg = in.facet,
      facet.ncol.arg = input$inPlotTrajFacetNcol,
280 281 282
      facet.color.arg = loc.facet.col, 
      dt.stim.arg = loc.dt.stim, 
      x.stim.arg = c('tstart', 'tend'),
dmattek's avatar
dmattek committed
283 284
      y.stim.arg = c('ystart', 'yend'), 
      stim.bar.width.arg = 1,
dmattek's avatar
Mod:  
dmattek committed
285 286 287 288
      xlab.arg = 'Time (min)',
      line.col.arg = loc.line.col.arg,
      aux.label1 = if (locPos) 'pos.x' else NULL,
      aux.label2 = if (locPos) 'pos.y' else NULL,
289
      aux.label3 = if (locObjNum) 'obj.num' else NULL,
290
      stat.arg = input$chBPlotTrajStat,
291
      ylim.arg = c(input$inSetColBoundsLow, input$inSetColBoundsHigh)
dmattek's avatar
Mod:  
dmattek committed
292 293 294 295 296
    )
    
    return(p.out)
  }
}