distPlot.R 9.27 KB
Newer Older
dmattek's avatar
dmattek committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
#
# Time Course Inspector: Shiny app for plotting time series data
# Author: Maciej Dobrzynski
#
# This module is for plotting distrubutions at selected time points as a choice of box/violin/dot-plots
# Assumes in.data contains columns:
# realtime
# y
# group
# id

# UI ----
modDistPlotUI =  function(id, label = "Plot distributions") {
  ns <- NS(id)
  
  tagList(
    fluidRow(
      column(
        4,
        checkboxInput(ns("chBplotTypeBox"),  "Box-plot", value = T),
        checkboxInput(ns("chBplotTypeDot"),  "Dot-plot", value = F),
        checkboxInput(ns("chBplotTypeViol"), "Violin-plot", value = F),
        checkboxInput(ns("chBplotTypeLine"), "Line-plot", value = F),
        checkboxInput(ns('chBplotInt'), 'Interactive Plot'),
        actionButton(ns('butPlot'), 'Plot!')
      ),
      column(
        4,
        uiOutput(ns('uiPlotBoxNotches')),
        uiOutput(ns('uiPlotBoxOutliers')),
        uiOutput(ns('uiPlotBoxDodge')),
        uiOutput(ns('uiPlotBoxAlpha')),
        uiOutput(ns('uiPlotDotNbins')),
        uiOutput(ns('uiPlotDotAlpha')),
        uiOutput(ns('uiPlotViolAlpha')),
        uiOutput(ns('uiPlotLineAlpha'))
      ),
      column(
        4,
        selectInput(
          ns('selPlotBoxLegendPos'),
          label = 'Legend position',
          choices = list(
            "Top" = 'top',
            "Right" = 'right',
            "Bottom" = 'bottom'
          ), 
          width = "120px",
          selected = 'top'
        ),
        radioButtons(ns("rBAxisLabelsRotate"), "X-axis labels",
                     c("horizontal" = 0,
                       "45 deg" = 45,
                       "90 deg" = 90)),
        numericInput(
          ns('inPlotBoxWidth'),
          'Width [%]',
          value = PLOTWIDTH,
          min = 10,
          width = '100px',
          step = 10
        ),
        numericInput(
          ns('inPlotBoxHeight'),
          'Height [px]',
          value = PLOTBOXHEIGHT,
          min = 100,
          width = '100px',
          step = 50
        )
      )
    ),
    
    uiOutput(ns('uiPlotBox')),
dmattek's avatar
dmattek committed
75
    downPlotUI(ns('downPlotBox'), "Download Plot")
dmattek's avatar
dmattek committed
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 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 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  )
}

# SERVER ----
modDistPlot = function(input, output, session, 
                      in.data,                       # input data table in long format
                      in.cols = list(meas.x = COLRT, # column names
                                     meas.y = COLY,
                                     group = COLGR,
                                     id = COLID), 
                      in.labels = list(x = "",       # plot labels
                                       y = "", 
                                       legend = ""),
                      in.fname) {                      # file name for saving the plot

  ns <- session$ns
  
  output$uiPlotBoxNotches = renderUI({
    cat(file = stderr(), 'boxPlot:uiPlotBoxNotches\n')
    
    ns <- session$ns
    
    if(input$chBplotTypeBox)
      checkboxInput(ns('chBplotBoxNotches'), 'Notches in box-plot ', FALSE)
  })
  
  output$uiPlotBoxOutliers = renderUI({
    cat(file = stderr(), 'boxPlot:uiPlotBoxOutliers\n')
    
    ns <- session$ns
    
    if(input$chBplotTypeBox)
      checkboxInput(ns('chBplotBoxOutliers'), 'Outliers in box-plot', FALSE)
  })
  
  output$uiPlotBoxDodge = renderUI({
    cat(file = stderr(), 'boxPlot:uiPlotBoxDodge\n')
    
    ns <- session$ns
    
    # Adjust spacing between box-, violin-, dot-plots.
    # Valid only when plotting multiple groups at a time point.
    # For line plot, each group is drawn separately per facet, thus no need for dodging..
    
    if(!input$chBplotTypeLine)
      sliderInput(ns('slPlotBoxDodge'), 'Space between groups', min = 0, max = 1, value = .4, step = 0.05)
  })
  
  output$uiPlotBoxAlpha = renderUI({
    cat(file = stderr(), 'boxPlot:uiPlotBoxAlpha\n')
    
    ns <- session$ns
    
    if(input$chBplotTypeBox)
      sliderInput(ns('slPlotBoxAlpha'), 'Box-plot transparency', min = 0, max = 1, value = 1, step = 0.1)
  })
  
  output$uiPlotViolAlpha = renderUI({
    cat(file = stderr(), 'boxPlot:uiPlotViolAlpha\n')
    
    ns <- session$ns
    
    if(input$chBplotTypeViol)
      sliderInput(ns('slPlotViolAlpha'), 'Violin-plot transparency', min = 0, max = 1, value = 1, step = 0.1)
  })
  
  output$uiPlotDotAlpha = renderUI({
    cat(file = stderr(), 'boxPlot:uiPlotDotAlpha\n')
    
    ns <- session$ns
    
    if(input$chBplotTypeDot)
      sliderInput(ns('slPlotDotAlpha'), 'Dot-plot transparency', min = 0, max = 1, value = 1, step = 0.1)
  })
  
  output$uiPlotLineAlpha = renderUI({
    cat(file = stderr(), 'boxPlot:uiPlotLineAlpha\n')
    
    ns <- session$ns
    
    if(input$chBplotTypeLine)
      sliderInput(ns('slPlotLineAlpha'), 'Line-plot transparency', min = 0, max = 1, value = 1, step = 0.1)
  })
  
  output$uiPlotDotNbins = renderUI({
    cat(file = stderr(), 'boxPlot:uiPlotDotNbins\n')
    
    ns <- session$ns
    
    if(input$chBplotTypeDot)
      sliderInput(ns('slPlotDotNbins'), 'Number of bins in dot-plot', min = 2, max = 50, value = 30, step = 1)
  })
  
  # Boxplot - display
  output$outPlotBox = renderPlot({
    
    plotBox()
    
  })
  
  
  output$outPlotBoxInt = 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)
    
    return( ggplotly(plotBox())  %>% layout(boxmode = 'group', width = '100%', height = '100%'))
    
  })
  
  
  output$uiPlotBox <- renderUI({
    ns <- session$ns
    
    if (input$chBplotInt)
      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'))
  })
  
  # Boxplot - download pdf
  callModule(downPlot, "downPlotBox", in.fname, 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')
213
    locBut = input$butPlot
dmattek's avatar
dmattek committed
214
    
215 216 217 218 219 220 221
    # Check if main data exists
    # Thanks to solate all mods in the left panel are delayed 
    # until clicking the Plot button
    loc.dt = isolate(in.data())
    validate(
      need(!is.null(loc.dt), "Nothing to plot. Load data first!")
    )    
dmattek's avatar
dmattek committed
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 260 261 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
    
    cat(file = stderr(), 'plotBox:dt not NULL\n')
    
    if(!input$chBplotTypeLine) {
      # Dodging series only for box-, dot-, and violin-plots 
      loc.par.dodge <- position_dodge(width = input$slPlotBoxDodge)
      
      # Color fill for all oplots except line, in which groups are plotted per facet
      p.out = ggplot(loc.dt, aes_string(x = sprintf("factor(%s)", in.cols$meas.x), 
                                        y = in.cols$meas.y,
                                        fill = in.cols$group)) 
      
    }
    else {
      loc.par.dodge = position_dodge(width = 1)
      p.out = ggplot(loc.dt, aes_string(x = sprintf("factor(%s)", in.cols$meas.x), 
                                        y = in.cols$meas.y)) 
      
    }
    
    
    if(input$chBplotTypeDot)
      p.out = p.out + geom_dotplot(color = NA,
                                   binaxis = "y", 
                                   stackdir = "center", 
                                   position = loc.par.dodge, 
                                   binwidth = abs(max(loc.dt[[ in.cols$meas.y ]], 
                                                      na.rm = T) - 
                                                    min(loc.dt[[ in.cols$meas.y ]], 
                                                        na.rm = T)) / (input$slPlotDotNbins - 1), 
                                   method = 'histodot',
                                   alpha = input$slPlotDotAlpha)
    
    if(input$chBplotTypeViol)
      p.out = p.out + 
      geom_violin(position = loc.par.dodge,
                  width = 0.2,
                  alpha = input$slPlotViolAlpha)
    
    if(input$chBplotTypeLine)
      p.out = p.out + 
        geom_path(aes_string(group = in.cols$id),
                  alpha = input$slPlotLineAlpha) +
        facet_wrap(as.formula(paste("~", in.cols$group)))
    
    if (input$chBplotTypeBox)
      p.out = p.out + geom_boxplot(
        position = loc.par.dodge,
        notch = input$chBplotBoxNotches, 
        alpha = input$slPlotBoxAlpha,
        outlier.colour = if (input$chBplotBoxOutliers)
          'red'
        else
          NA
      ) 
    
    p.out = p.out +
      scale_fill_discrete(name = in.labels$legend) +
      xlab(in.labels$x) +
      ylab(in.labels$y) +
      LOCggplotTheme(in.font.base = PLOTFONTBASE, 
                     in.font.axis.text = PLOTFONTAXISTEXT, 
                     in.font.axis.title = PLOTFONTAXISTITLE, 
                     in.font.strip = PLOTFONTFACETSTRIP, 
                     in.font.legend = PLOTFONTLEGEND) + 
      theme(legend.position = input$selPlotBoxLegendPos,
            axis.text.x = LOCrotatedAxisElementText(as.numeric(input$rBAxisLabelsRotate), 
                                                    size = PLOTFONTAXISTEXT))
    
    
    return(p.out)
  }
  
}