tabBoxPlot.R 12.2 KB
Newer Older
dmattek's avatar
Added:  
dmattek committed
1 2 3 4 5 6
require(DT)

tabBoxPlotUI =  function(id, label = "Comparing t-points") {
  ns <- NS(id)
  
  tagList(
dmattek's avatar
Mod:  
dmattek committed
7 8 9 10 11
    h4(
      "Box-/dot-/violin plot at selected time points"
    ),
    br(),
    
dmattek's avatar
Added:  
dmattek committed
12 13
    uiOutput(ns('varSelTpts')),
    
dmattek's avatar
Mod:  
dmattek committed
14 15 16
    checkboxInput(ns('chbTabStats'), 'Show stats', FALSE),
    uiOutput(ns('uiTabStats')),
    uiOutput(ns('uiDownSingleCellData')),
dmattek's avatar
Added:  
dmattek committed
17
    
dmattek's avatar
Mod:  
dmattek committed
18
    br(),
dmattek's avatar
Added:  
dmattek committed
19 20
    fluidRow(
      column(
dmattek's avatar
Added:  
dmattek committed
21
        4,
dmattek's avatar
Added:  
dmattek committed
22 23 24 25
        checkboxGroupInput(ns('inPlotType'), 'Plot type:', list('Dot-plot' = 'dot', 
                                                                'Violin-plot' = 'viol',
                                                                'Box-plot' = 'box', 
                                                                'Line-plot' = 'line'), selected = 'box'),
dmattek's avatar
Added:  
dmattek committed
26 27
        checkboxInput(ns('chBPlotBoxInt'), 'Interactive Plot?'),
        actionButton(ns('butPlotBox'), 'Plot!')
dmattek's avatar
Added:  
dmattek committed
28 29
      ),
      column(
dmattek's avatar
Added:  
dmattek committed
30
        4,
dmattek's avatar
Added:  
dmattek committed
31 32 33 34 35 36 37 38 39
        selectInput(
          ns('selPlotBoxLegendPos'),
          label = 'Select legend position',
          choices = list(
            "Top" = 'top',
            "Right" = 'right',
            "Bottom" = 'bottom'
          ),
          selected = 'top'
dmattek's avatar
Mod:  
dmattek committed
40 41 42
        ),
        uiOutput(ns('uiPlotBoxNotches')),
        uiOutput(ns('uiPlotBoxOutliers')),
dmattek's avatar
Fixed:  
dmattek committed
43 44
        uiOutput(ns('uiPlotBoxDodge')),
        #uiOutput(ns('uiPlotBoxWidth')),
dmattek's avatar
Added:  
dmattek committed
45
        uiOutput(ns('uiPlotBoxAlpha')),
dmattek's avatar
Mod:  
dmattek committed
46
        uiOutput(ns('uiPlotDotNbins'))
dmattek's avatar
Added:  
dmattek committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
      ),
      column(
        4,
        numericInput(
          ns('inPlotBoxWidth'),
          'Width [%]:',
          value = 100,
          min = 10,
          width = '100px',
          step = 10
        ),
        numericInput(
          ns('inPlotBoxHeight'),
          'Height [px]:',
          value = 800,
          min = 100,
          width = '100px',
          step = 50
        )
dmattek's avatar
Added:  
dmattek committed
66 67
      )
    ),
dmattek's avatar
Added:  
dmattek committed
68 69
    
    uiOutput(ns('uiPlotBox')),
dmattek's avatar
Added:  
dmattek committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 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
    downPlotUI(ns('downPlotBox'), "Download PDF")
  )
  
}

####
## server box-plot
tabBoxPlot = function(input, output, session, in.data) {
  # return all unique time points (real time)
  # This will be used to display in UI for box-plot
  # These timepoints are from the original dt and aren't affected by trimming of x-axis
  getDataTpts <- reactive({
    cat(file = stderr(), 'getDataTpts\n')
    loc.dt = in.data()
    
    if (is.null(loc.dt))
      return(NULL)
    else
      return(unique(loc.dt[, realtime])) # column name specified in data4trajPlot
  })
  
  # prepare data for plotting boxplots
  # uses the same dt as for trajectory plotting
  # returns dt with these columns:
  data4boxPlot <- reactive({
    cat(file = stderr(), 'data4boxPlot\n')
    
    loc.dt = in.data()
    if (is.null(loc.dt))
      return(NULL)
    
    loc.out = loc.dt[realtime %in% input$inSelTpts]
  })
  
  output$varSelTpts = renderUI({
    cat(file = stderr(), 'UI varSelTpts\n')
    
    ns <- session$ns
    
    loc.v = getDataTpts()
    if (!is.null(loc.v)) {
      selectInput(
        ns('inSelTpts'),
        'Select one or more timepoints:',
        loc.v,
        width = '100%',
        selected = 0,
        multiple = TRUE
      )
    }
  })
dmattek's avatar
Mod:  
dmattek committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

  output$uiTabStats = renderUI({
    cat(file = stderr(), 'UI uiTabStats\n')
    ns <- session$ns
    
    if(input$chbTabStats) {
      DT::dataTableOutput(ns('outTabStats'))
    }
  })
  
  output$uiDownSingleCellData = renderUI({
    cat(file = stderr(), 'UI uiDownSingleCellData\n')
    ns <- session$ns
    
    if(input$chbTabStats) {
      downloadButton(ns('downloadData4BoxPlot'), 'Download single-cell data')
    }
  })
dmattek's avatar
Added:  
dmattek committed
139 140 141 142 143 144
  
  output$uiPlotBoxNotches = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxNotches\n')
    
    ns <- session$ns
    
dmattek's avatar
Added:  
dmattek committed
145 146
    if('box' %in% input$inPlotType)
       checkboxInput(ns('inPlotBoxNotches'), 'Box plot notches?', FALSE)
dmattek's avatar
Added:  
dmattek committed
147 148 149 150 151 152 153
  })
  
  output$uiPlotBoxOutliers = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxNotches\n')
    
    ns <- session$ns
    
dmattek's avatar
Added:  
dmattek committed
154
    if('box' %in% input$inPlotType)
dmattek's avatar
Added:  
dmattek committed
155 156 157
      checkboxInput(ns('inPlotBoxOutliers'), 'Box plot outliers?', FALSE)
  })
  
dmattek's avatar
Fixed:  
dmattek committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
  output$uiPlotBoxDodge = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxDodge\n')
    
    ns <- session$ns
    
    if(!( input$inPlotType %in% 'line' ))
      sliderInput(ns('inPlotBoxDodge'), 'Dodge series:', min = 0, max = 1, value = .4, step = 0.05)
  })

  output$uiPlotBoxWidth = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxWidth\n')
    
    ns <- session$ns
    
    if('box' %in% input$inPlotType)
      sliderInput(ns('inPlotBoxWidth'), 'Box plot width:', min = 0, max = 1, value = .2, step = 0.1)
  })
  
dmattek's avatar
Added:  
dmattek committed
176 177 178 179 180 181
  output$uiPlotBoxAlpha = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxAlpha\n')
    
    ns <- session$ns
    
    if('box' %in% input$inPlotType)
dmattek's avatar
Fixed:  
dmattek committed
182
      sliderInput(ns('inPlotBoxAlpha'), 'Box plot transparency:', min = 0, max = 1, value = 1, step = 0.05)
dmattek's avatar
Added:  
dmattek committed
183 184
  })
  
dmattek's avatar
Added:  
dmattek committed
185 186 187 188 189
  output$uiPlotDotNbins = renderUI({
    cat(file = stderr(), 'UI uiPlotDotNbins\n')
    
    ns <- session$ns
    
dmattek's avatar
Added:  
dmattek committed
190 191
    if('dot' %in% input$inPlotType)
      sliderInput(ns('inPlotDotNbins'), 'Dot-plot bin size (10^x):', min = -4, max = 4, value = -1.5, step = 0.1)
dmattek's avatar
Added:  
dmattek committed
192 193 194 195 196 197 198 199 200 201
  })
  
  
  calcStats = reactive({
    cat(file = stderr(), 'tabBoxPlot: calsStats\n')
    loc.dt = data4boxPlot()
    
    if (is.null(loc.dt))
      return(NULL)
    
dmattek's avatar
Mod:  
dmattek committed
202 203 204 205 206 207 208 209 210
    loc.dt.aggr = loc.dt[, sapply(.SD, function(x) list('N' = .N, 
                                                        'Mean' = mean(x), 
                                                        'CV' = sd(x)/mean(x), 
                                                        'Median' = median(x), 
                                                        'rCV (IQR)' = IQR(x)/median(x), 
                                                        'rCV (MAD)'= mad(x)/median(x))), .SDcols = c('y'), by = .(realtime, group)]
    
    setnames(loc.dt.aggr, c('Time point', 'Group','N', 'Mean', 'CV', 'Median', 'rCV IQR', 'rCV MAD'))
    #print(loc.dt.aggr)
dmattek's avatar
Added:  
dmattek committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    return(loc.dt.aggr)
  })
  
  output$downloadData4BoxPlot <- downloadHandler(
    filename = 'data4boxplot.csv',
    content = function(file) {
      write.csv(data4boxPlot(), file, row.names = FALSE)
    }
  )
  
  
  # output$outTabStats = DT::renderDataTable(calcStats(), 
  #                                          server = FALSE, 
  #                                          rownames = FALSE,
  #                                          extensions = 'Buttons', 
  #                                          options = list(
  #                                            dom = 'Bfrtip',
  #                                            buttons = list('copy', 
  #                                                           'print', 
  #                                                           list(extend = 'collection',
  #                                                                buttons = list(list(extend='csv',
  #                                                                                    filename = 'hitStats'),
  #                                                                               list(extend='excel',
  #                                                                                    filename = 'hitStats'),
  #                                                                               list(extend='pdf',
  #                                                                                    filename= 'hitStats')),
  #                                                                text = 'Download'))))
  # 
  output$outTabStats = DT::renderDataTable(server = FALSE, {
    cat(file = stderr(), 'tabBoxPlot: outTabStats\n')
    loc.dt = calcStats()

    if (is.null(loc.dt))
      return(NULL)

    datatable(loc.dt, 
              rownames = FALSE,
              extensions = 'Buttons', 
              options = list(
                dom = 'Bfrtip',
                buttons = list('copy', 
                               'print', 
                               list(extend = 'collection',
                                    buttons = list(list(extend='csv',
                                                        filename = 'hitStats'),
                                                   list(extend='excel',
                                                        filename = 'hitStats'),
                                                   list(extend='pdf',
                                                        filename= 'hitStats')),
dmattek's avatar
Mod:  
dmattek committed
260
                                    text = 'Download')))) %>% formatRound(4:8, 3)
dmattek's avatar
Added:  
dmattek committed
261 262 263 264 265 266 267 268 269 270 271 272 273
  })
  
  # Boxplot - display
  output$outPlotBox = renderPlot({
    locBut = input$butPlotBox
    
    if (locBut == 0) {
      cat(file = stderr(), 'plotBox: Go button not pressed\n')
      return(NULL)
    }
    
    plotBox()
    
dmattek's avatar
Added:  
dmattek committed
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
  })
  

  output$outPlotBoxInt = renderPlotly({
    locBut = input$butPlotBox
    
    if (locBut == 0) {
      cat(file = stderr(), 'plotBox: Go button not pressed\n')
      return(NULL)
    }
    
    # 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)
    
    return( ggplotly(plotBox())  %>% layout(boxmode = 'group', width = '100%', height = '100%'))
    
  })
  
  
  output$uiPlotBox <- renderUI({
    ns <- session$ns
    
    if (input$chBPlotBoxInt)
      plotlyOutput(ns("outPlotBoxInt"), 
                   width = paste0(input$inPlotBoxWidth, '%'),
                   height = paste0(input$inPlotBoxHeight, 'px'))
    else
      plotOutput(ns('outPlotBox'),
                 width = paste0(input$inPlotBoxWidth, '%'),
                 height = paste0(input$inPlotBoxHeight, 'px'))
  })
dmattek's avatar
Added:  
dmattek committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
  
  # Boxplot - download pdf
  callModule(downPlot, "downPlotBox", 'boxplot.pdf', plotBox, TRUE)
  
  # Function instead of reactive as per:
  # http://stackoverflow.com/questions/26764481/downloading-png-from-shiny-r
  # This function is used to plot and to downoad a pdf
  
  plotBox <- function() {
    cat(file = stderr(), 'plotBox\n')
    
    loc.dt = data4boxPlot()
    
    cat(file = stderr(), "plotBox: on to plot\n\n")
    if (is.null(loc.dt)) {
      cat(file = stderr(), 'plotBox: dt is NULL\n')
      return(NULL)
    }
    
    cat(file = stderr(), 'plotBox:dt not NULL\n')
    
    
dmattek's avatar
Fixed:  
dmattek committed
331
    loc.par.dodge <- position_dodge(width = input$inPlotBoxDodge)
dmattek's avatar
Added:  
dmattek committed
332
    p.out = ggplot(loc.dt, aes(x = as.factor(realtime), y = y)) 
dmattek's avatar
Added:  
dmattek committed
333
    
dmattek's avatar
Added:  
dmattek committed
334
    if('dot' %in% input$inPlotType)
dmattek's avatar
Fixed:  
dmattek committed
335 336 337 338 339 340
      p.out = p.out + geom_dotplot(aes(fill = group), 
                                   binaxis = "y", 
                                   stackdir = "center", 
                                   position = loc.par.dodge, 
                                   binwidth = 10^(input$inPlotDotNbins), 
                                   method = 'histodot')
dmattek's avatar
Added:  
dmattek committed
341 342 343 344 345 346 347 348 349 350 351 352
    
    if('viol' %in% input$inPlotType)
      p.out = p.out + geom_violin(aes(fill = group),
                                  position = loc.par.dodge,
                                  width = 0.2)

    if('line' %in% input$inPlotType)
      p.out = p.out + 
      geom_path(aes(color = group, group = id)) +
      facet_wrap(~ group)
    
    if ('box' %in% input$inPlotType)
dmattek's avatar
Added:  
dmattek committed
353
      p.out = p.out + geom_boxplot(
dmattek's avatar
Added:  
dmattek committed
354 355
        aes(fill = group), 
        position = loc.par.dodge,
dmattek's avatar
Fixed:  
dmattek committed
356
        #width = 0.2, #input$inPlotBoxWidth,
dmattek's avatar
Added:  
dmattek committed
357 358
        notch = input$inPlotBoxNotches, 
        alpha = input$inPlotBoxAlpha,
dmattek's avatar
Added:  
dmattek committed
359 360 361 362
        outlier.colour = if (input$inPlotBoxOutliers)
          'red'
        else
          NA
dmattek's avatar
Added:  
dmattek committed
363
      ) 
dmattek's avatar
Added:  
dmattek committed
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    
    p.out = p.out +
      scale_fill_discrete(name = '') +
      xlab('\nTime (min)') +
      ylab('') +
      theme_bw(base_size = 18, base_family = "Helvetica") +
      theme(
        panel.grid.minor = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_blank(),
        axis.line.x = element_line(color = "black", size = 0.25),
        axis.line.y = element_line(color = "black", size = 0.25),
        axis.text.x = element_text(size = 12),
        axis.text.y = element_text(size = 12),
        strip.text.x = element_text(size = 14, face = "bold"),
        strip.text.y = element_text(size = 14, face = "bold"),
        strip.background = element_blank(),
        legend.key = element_blank(),
        legend.key.height = unit(1, "lines"),
        legend.key.width = unit(2, "lines"),
        legend.position = input$selPlotBoxLegendPos
      )
    
    return(p.out)
  }
  
}