tabScatter.R 8.96 KB
Newer Older
dmattek's avatar
dmattek committed
1
2
3
4
5
6
#
# Time Course Inspector: Shiny app for plotting time series data
# Author: Maciej Dobrzynski
#
# This module is a tab for plotting scatter plots between two time points
#
dmattek's avatar
dmattek committed
7
8
9
10
11
12
13
14
15
16
# Use:
# in ui.R
# tabPanel(
#  'Hierarchical',
#  clustHierUI('TabClustHier'))
#
# in server.R
# callModule(clustHier, 'TabClustHier', dataMod)
# where dataMod is the output from a reactive function that returns dataset ready for clustering

dmattek's avatar
dmattek committed
17
18
19
20
21
22
23
24
helpText.tabScatter = c("Display measurement values from two different time points as a scatter plot.",
                  'Y-axis can display a value at a selected time point or a difference between values at two selected time points.', #1
                  'Add a line with linear regression and regions of 95% confidence interval.', #2
                  'A number of time points left & right of selected time points; use the mean of values from these time points for the scatterplot.', #3
                  'Height in pixels of the displayed plot', #4
                  'Number of facets in a row. Each facet displayes a scatter plot for a single group.' #5
)

dmattek's avatar
dmattek committed
25
# UI ----
dmattek's avatar
dmattek committed
26
27
28
29
30
tabScatterPlotUI <- function(id, label = "Comparing t-points") {
  ns <- NS(id)
  
  tagList(
    h4(
dmattek's avatar
dmattek committed
31
      "Scatter plot between two time points"
dmattek's avatar
dmattek committed
32
    ),
dmattek's avatar
dmattek committed
33
    actionLink(ns("alScatter"), "Learn more"),
dmattek's avatar
dmattek committed
34
35
36
37
    br(),
    
    fluidRow(
      column(
38
39
40
        4,
        uiOutput(ns('uiSelTptX')),
        uiOutput(ns('uiSelTptY')),
dmattek's avatar
dmattek committed
41
        bsAlert("alert2differentTpts"),
dmattek's avatar
dmattek committed
42
        checkboxInput(ns('chBregression'), 'Linear regression with 95% CI'),
dmattek's avatar
dmattek committed
43
        bsTooltip(ns('chBregression'), helpText.tabScatter[3], placement = "bottom", trigger = "hover", options = NULL)
dmattek's avatar
Added:    
dmattek committed
44
45
46
      ),
      column(
        4, 
dmattek's avatar
dmattek committed
47
48
49
50
51
52
53
54
        numericInput(ns('inNeighTpts'), 'Smoothing', value = 0, step = 1, min = 0, width = "120px"),
        bsTooltip(ns('inNeighTpts'), helpText.tabScatter[4], placement = "bottom", trigger = "hover", options = NULL),

        radioButtons(ns('rBfoldChange'), 'Y-axis', 
                     choices = c("Y" = "y", "Y-X" = "diff"), 
                     width = "100px", inline = T),
        bsTooltip(ns('rBfoldChange'), helpText.tabScatter[2], placement = "bottom", trigger = "hover", options = NULL)
        
dmattek's avatar
dmattek committed
55
56
      ),
      column(
57
        4,
dmattek's avatar
dmattek committed
58
59
        numericInput(
          ns('inPlotHeight'),
dmattek's avatar
dmattek committed
60
          'Height [px]',
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
61
          value = PLOTSCATTERHEIGHT,
dmattek's avatar
dmattek committed
62
          min = 100,
dmattek's avatar
dmattek committed
63
64
          step = 100,
          width = "100px"
dmattek's avatar
dmattek committed
65
        ),
dmattek's avatar
dmattek committed
66
67
        bsTooltip(ns('inPlotHeight'), helpText.tabScatter[5], placement = "bottom", trigger = "hover", options = NULL),

dmattek's avatar
dmattek committed
68
69
        numericInput(
          ns('inPlotNcolFacet'),
dmattek's avatar
dmattek committed
70
          '#columns',
71
          value = PLOTNFACETDEFAULT,
dmattek's avatar
dmattek committed
72
          min = 1,
dmattek's avatar
dmattek committed
73
74
          step = 1,
          width = "100px"
dmattek's avatar
dmattek committed
75
76
        ),
        bsTooltip(ns('inPlotNcolFacet'), helpText.tabScatter[6], placement = "bottom", trigger = "hover", options = NULL)
dmattek's avatar
dmattek committed
77
78
79
80
81
82
83
      )
    ),
    
    br(),
    checkboxInput(ns('plotInt'), 
                  'Interactive Plot?',
                  value = FALSE),
dmattek's avatar
Added:    
dmattek committed
84
    actionButton(ns('butGoScatter'), 'Plot!'),
dmattek's avatar
dmattek committed
85
86
87
88
89
    uiOutput(ns("plotInt_ui")),
    downPlotUI(ns('downPlotScatter'), "Download PDF")
  )
}

dmattek's avatar
dmattek committed
90
# SERVER ----
91
tabScatterPlot <- function(input, output, session, in.data, in.fname) {
dmattek's avatar
dmattek committed
92
  
dmattek's avatar
dmattek committed
93
94
  ns <- session$ns
  
dmattek's avatar
dmattek committed
95
96
97
98
99
100
101
102
103
104
# 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
dmattek's avatar
dmattek committed
105
    return(unique(loc.dt[[COLRT]]))
dmattek's avatar
dmattek committed
106
107
})

108
output$uiSelTptX = renderUI({
dmattek's avatar
dmattek committed
109
  cat(file = stderr(), 'tabScatter:uiSelTptX\n')
dmattek's avatar
dmattek committed
110
111
112
113
114
115
116
  
  ns <- session$ns
  
  loc.v = getDataTpts()
  if (!is.null(loc.v)) {
    selectInput(
      ns('inSelTptX'),
dmattek's avatar
dmattek committed
117
      'Time point for X-axis',
dmattek's avatar
dmattek committed
118
      loc.v,
dmattek's avatar
dmattek committed
119
      width = '180px',
dmattek's avatar
dmattek committed
120
121
122
123
124
125
      selected = 0,
      multiple = FALSE
    )
  }
})

126
output$uiSelTptY = renderUI({
dmattek's avatar
dmattek committed
127
  cat(file = stderr(), 'tabScatter:uiSelTptY\n')
dmattek's avatar
dmattek committed
128
129
130
131
132
133
134
  
  ns <- session$ns
  
  loc.v = getDataTpts()
  if (!is.null(loc.v)) {
    selectInput(
      ns('inSelTptY'),
dmattek's avatar
dmattek committed
135
      'Time point for Y-axis',
dmattek's avatar
dmattek committed
136
      loc.v,
dmattek's avatar
dmattek committed
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
      width = '180px',
      selected = 1,
      multiple = FALSE
    )
  }
})

output$uiNcolFacet = renderUI({
  cat(file = stderr(), 'tabScatter:uiNcolFacet\n')
  
  ns <- session$ns
  
  loc.v = getDataTpts()
  if (!is.null(loc.v)) {
    selectInput(
      ns('inSelTptY'),
      'Time point for Y-axis',
      loc.v,
      width = '180px',
dmattek's avatar
dmattek committed
156
      selected = 1,
dmattek's avatar
dmattek committed
157
158
159
160
161
162
163
164
165
166
167
168
      multiple = FALSE
    )
  }
})

data4scatterPlot <- reactive({
  cat(file = stderr(), 'data4scatterPlot\n')
  
  loc.dt.in = in.data()
  if(is.null(loc.dt.in))
    return(NULL)
  
dmattek's avatar
dmattek committed
169
170
171
  # obtain selected time points from UI
  loc.tpts.x = as.integer(input$inSelTptX)
  loc.tpts.y = as.integer(input$inSelTptY)
dmattek's avatar
dmattek committed
172
  
dmattek's avatar
dmattek committed
173
174
175
176
177
178
179
180
181
182
  if (loc.tpts.x == loc.tpts.y) {
    createAlert(session, "alert2differentTpts", "exampleAlert", title = "",
                content = "Select two different time points.", append = FALSE)
    return(NULL)
    
  } else {
    closeAlert(session, "exampleAlert")    
  }
  
  # if neigbbouring points selected, obtain time points for which the aggregation will be calculated
183
  if (input$inNeighTpts > 0) {
dmattek's avatar
dmattek committed
184
    # get all time points in the dataset
dmattek's avatar
dmattek committed
185
    loc.dt.in.tpts = unique(loc.dt.in[[COLRT]])
186
    
dmattek's avatar
dmattek committed
187
    # get indices of time points around selected time points
188
189
190
    loc.tpts.x.id = seq(which(loc.dt.in.tpts == loc.tpts.x) - input$inNeighTpts, which(loc.dt.in.tpts == loc.tpts.x) + input$inNeighTpts, 1)
    loc.tpts.y.id = seq(which(loc.dt.in.tpts == loc.tpts.y) - input$inNeighTpts, which(loc.dt.in.tpts == loc.tpts.y) + input$inNeighTpts, 1)
    
dmattek's avatar
dmattek committed
191
    # get only indices of time points that are greater than 0
192
193
194
    loc.tpts.x.id = loc.tpts.x.id[loc.tpts.x.id > 0]
    loc.tpts.y.id = loc.tpts.y.id[loc.tpts.y.id > 0]
    
dmattek's avatar
dmattek committed
195
    # update time points used for aggregation
196
197
    loc.tpts.x = loc.dt.in.tpts[loc.tpts.x.id]
    loc.tpts.y = loc.dt.in.tpts[loc.tpts.y.id]
dmattek's avatar
dmattek committed
198
199
200
201

    # aggregate separately each time point sets
    loc.dt.x = loc.dt.in[get(COLRT) %in% loc.tpts.x, .(y.aggr = mean(get(COLY))), by = c(COLGR, COLID)]
    loc.dt.y = loc.dt.in[get(COLRT) %in% loc.tpts.y, .(y.aggr = mean(get(COLY))), by = c(COLGR, COLID)]
202
    
dmattek's avatar
dmattek committed
203
204
205
206
207
    loc.dt = merge(loc.dt.x, loc.dt.y, by = COLID)
    loc.dt[, group.y := NULL]
    
    setnames(loc.dt, c('group.x', 'y.aggr.x', 'y.aggr.y'), c(COLGR, 'x', 'y'))

208
209
210
    #cat(loc.tpts.x.id, '\n')
    #cat(loc.tpts.y.id, '\n')
  } else {
dmattek's avatar
dmattek committed
211
212
213
214
215
216
217
218
219
    # get data from selected time points
    loc.dt = loc.dt.in[get(COLRT) %in% c(loc.tpts.x, loc.tpts.y)]

    # convert to wide, such that two selected time points are in two columns
    loc.dt = dcast(loc.dt[, c(COLGR, COLID, COLY, COLRT), with = F], 
                   as.formula(paste0(COLGR, "+", COLID, "~", COLRT)),
                   value.var = COLY)
   
    setnames(loc.dt, c(COLGR, COLID, "x", "y"))
220
221
  }

dmattek's avatar
dmattek committed
222
223
  

dmattek's avatar
dmattek committed
224
  if (input$rBfoldChange == "diff") {
225
    loc.dt[ , y := y - x]
226
  }
dmattek's avatar
dmattek committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
  return(loc.dt)
  
})

  # 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
  
plotScatter <- function() {
  cat(file=stderr(), "plotScatter\n")
  
  # isolate because calculations & plotting take a while
  # re-plotting done upon button press
  loc.dt = isolate(data4scatterPlot())
dmattek's avatar
dmattek committed
241

dmattek's avatar
dmattek committed
242
243
244
245
246
247
248
249
250
  cat("plotScatter on to plot\n\n")
  if (is.null(loc.dt)) {
    cat(file=stderr(), 'plotScatter: dt is NULL\n')
    return(NULL)
  }
  
  cat(file=stderr(), 'plotScatter:dt not NULL\n')
  

dmattek's avatar
dmattek committed
251
  p.out = LOCggplotScat(
dmattek's avatar
dmattek committed
252
253
    dt.arg = loc.dt,
    plotlab.arg = NULL,
dmattek's avatar
dmattek committed
254
    facet.arg = COLGR,
dmattek's avatar
dmattek committed
255
    facet.ncol.arg = input$inPlotNcolFacet,
dmattek's avatar
dmattek committed
256
257
258
    alpha.arg = 0.5,
    trend.arg = input$chBregression,
    ci.arg = 0.95
dmattek's avatar
dmattek committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
  )
  return(p.out)
}

# display plot
output$outPlotScatter <- renderPlot({
  locBut = input$butGoScatter
  
  if (locBut == 0) {
    cat(file=stderr(), 'plotScatter: Go button not pressed\n')
    
    return(NULL)
  }
  
  plotScatter()
})



output$outPlotScatterInt <- 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
283
  
284
  locBut = input$butGoScatter
285
286
287
288
289
  if (locBut == 0) {
    cat(file=stderr(), 'plotScatterInt Go button not pressed\n')
    return(NULL)
  }
  
dmattek's avatar
dmattek committed
290
291
292
  if (names(dev.cur()) != "null device") dev.off()
  pdf(NULL)

dmattek's avatar
dmattek committed
293
  return(plotly_build(plotScatter()))
dmattek's avatar
dmattek committed
294
295
296
297
  
})

  # download pdf
298
  callModule(downPlot, "downPlotScatter", in.fname, plotScatter, TRUE)
dmattek's avatar
dmattek committed
299
  
dmattek's avatar
dmattek committed
300
  # Scatter plot - choose to display regular or interactive plot
dmattek's avatar
dmattek committed
301
302
303
  output$plotInt_ui <- renderUI({
    ns <- session$ns
    if (input$plotInt)
dmattek's avatar
dmattek committed
304
      tagList( withSpinner(plotlyOutput(ns("outPlotScatterInt"), height = paste0(input$inPlotHeight, "px"))))
dmattek's avatar
dmattek committed
305
    else
dmattek's avatar
dmattek committed
306
      tagList( withSpinner(plotOutput(ns('outPlotScatter'), height = paste0(input$inPlotHeight, "px"))))
dmattek's avatar
dmattek committed
307
308
  })
  
dmattek's avatar
dmattek committed
309
310
311
  addPopover(session, 
             id = ns("alScatter"), 
             title = "Scatter plot",
dmattek's avatar
dmattek committed
312
             content = helpText.tabScatter[1],
dmattek's avatar
dmattek committed
313
314
315
316
             trigger = "click")
  
  
  
dmattek's avatar
dmattek committed
317
}