boxPlot.R 7.52 KB
Newer Older
dmattek's avatar
Added:  
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
# Module for plotting a choice of box/violin/dot-plots
# Assumes in.data contains columns:
# realtime
# y
# group
# id

modBoxPlotUI =  function(id, label = "Plot Box-plots") {
  ns <- NS(id)
  
  tagList(
    fluidRow(
      column(
        4,
        checkboxGroupInput(ns('inPlotType'), 'Plot type:', list('Dot-plot' = 'dot', 
                                                                'Violin-plot' = 'viol',
                                                                'Box-plot' = 'box', 
                                                                'Line-plot' = 'line'), selected = 'box'),
        checkboxInput(ns('chBPlotBoxInt'), 'Interactive Plot?'),
        actionButton(ns('butPlotBox'), 'Plot!')
      ),
      column(
        4,
        selectInput(
          ns('selPlotBoxLegendPos'),
          label = 'Select legend position',
          choices = list(
            "Top" = 'top',
            "Right" = 'right',
            "Bottom" = 'bottom'
          ),
          selected = 'top'
        ),
        uiOutput(ns('uiPlotBoxNotches')),
        uiOutput(ns('uiPlotBoxOutliers')),
        uiOutput(ns('uiPlotBoxDodge')),
        #uiOutput(ns('uiPlotBoxWidth')),
        uiOutput(ns('uiPlotBoxAlpha')),
        uiOutput(ns('uiPlotDotNbins'))
      ),
      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
dmattek committed
58 59 60
        ),
        radioButtons(ns("rBAxisLabelsRotate"), "X-axis labels:",
                     c("horizontal" = 0,
dmattek's avatar
dmattek committed
61
                       "45 deg" = 45,
dmattek's avatar
dmattek committed
62
                       "90 deg" = 90))
dmattek's avatar
Added:  
dmattek committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
      )
    ),
    
    uiOutput(ns('uiPlotBox')),
    downPlotUI(ns('downPlotBox'), "Download PDF")
  )
}


modBoxPlot = function(input, output, session, 
                      in.data, 
                      in.cols = list(meas.x = 'realtime',
                                     meas.y = 'y',
                                     group = 'group',
                                     id = 'id'), 
78
                      in.fname) {
dmattek's avatar
Added:  
dmattek committed
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
  
  ns <- session$ns
 
  output$uiPlotBoxNotches = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxNotches\n')
    
    ns <- session$ns
    
    if('box' %in% input$inPlotType)
      checkboxInput(ns('inPlotBoxNotches'), 'Box plot notches?', FALSE)
  })
  
  output$uiPlotBoxOutliers = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxNotches\n')
    
    ns <- session$ns
    
    if('box' %in% input$inPlotType)
      checkboxInput(ns('inPlotBoxOutliers'), 'Box plot outliers?', FALSE)
  })
  
  output$uiPlotBoxDodge = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxDodge\n')
    
    ns <- session$ns
    
    if(!( 'line' %in% input$inPlotType  ))
      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)
  })
  
  output$uiPlotBoxAlpha = renderUI({
    cat(file = stderr(), 'UI uiPlotBoxAlpha\n')
    
    ns <- session$ns
    
    if('box' %in% input$inPlotType)
      sliderInput(ns('inPlotBoxAlpha'), 'Box plot transparency:', min = 0, max = 1, value = 1, step = 0.05)
  })
  
  output$uiPlotDotNbins = renderUI({
    cat(file = stderr(), 'UI uiPlotDotNbins\n')
    
    ns <- session$ns
    
    if('dot' %in% input$inPlotType)
      sliderInput(ns('inPlotDotNbins'), 'Dot-plot bin size (10^x):', min = -4, max = 4, value = -1.5, step = 0.1)
  })
  
  # Boxplot - display
  output$outPlotBox = renderPlot({
    locBut = input$butPlotBox
    
    if (locBut == 0) {
      cat(file = stderr(), 'plotBox: Go button not pressed\n')
      return(NULL)
    }
    
    plotBox()
    
  })
  
  
  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'))
  })
  
  # 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')
    
    loc.dt = in.data()
    
    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')
    
    loc.par.dodge <- position_dodge(width = input$inPlotBoxDodge)
    p.out = ggplot(loc.dt, aes_string(x = sprintf("factor(%s)", in.cols[['meas.x']]), y = in.cols[['meas.y']])) 
    
    if('dot' %in% input$inPlotType)
      p.out = p.out + geom_dotplot(aes_string(fill = in.cols[['group']]), 
dmattek's avatar
dmattek committed
208
                                   color = NA,
dmattek's avatar
Added:  
dmattek committed
209 210 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
                                   binaxis = "y", 
                                   stackdir = "center", 
                                   position = loc.par.dodge, 
                                   binwidth = 10^(input$inPlotDotNbins), 
                                   method = 'histodot')
    
    if('viol' %in% input$inPlotType)
      p.out = p.out + geom_violin(aes_string(fill = in.cols[['group']]),
                                  position = loc.par.dodge,
                                  width = 0.2)
    
    if('line' %in% input$inPlotType)
      p.out = p.out + 
      geom_path(aes_string(color = in.cols[['group']], group = in.cols[['id']])) +
      facet_wrap(as.formula(paste("~", in.cols[['group']])))
    
    if ('box' %in% input$inPlotType)
      p.out = p.out + geom_boxplot(
        aes_string(fill = in.cols[['group']]), 
        position = loc.par.dodge,
        #width = 0.2, #input$inPlotBoxWidth,
        notch = input$inPlotBoxNotches, 
        alpha = input$inPlotBoxAlpha,
        outlier.colour = if (input$inPlotBoxOutliers)
          'red'
        else
          NA
      ) 
    
    p.out = p.out +
      scale_fill_discrete(name = '') +
      xlab('') +
      ylab('') +
242 243 244 245 246
      LOCggplotTheme(in.font.base = PLOTFONTBASE, 
                     in.font.axis.text = PLOTFONTAXISTEXT, 
                     in.font.axis.title = PLOTFONTAXISTITLE, 
                     in.font.strip = PLOTFONTFACETSTRIP, 
                     in.font.legend = PLOTFONTLEGEND) + 
dmattek's avatar
dmattek committed
247
      theme(legend.position = input$selPlotBoxLegendPos,
dmattek's avatar
dmattek committed
248
            axis.text.x = LOCrotatedAxisElementText(as.numeric(input$rBAxisLabelsRotate)))
dmattek's avatar
dmattek committed
249

dmattek's avatar
Added:  
dmattek committed
250 251 252 253 254
    
    return(p.out)
  }
  
}