-
Notifications
You must be signed in to change notification settings - Fork 19
/
app.R
1526 lines (1123 loc) · 57.3 KB
/
app.R
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
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
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
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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# PlotsOfData: Shiny app for plotting and comparing the data
# Created by Joachim Goedhart (@joachimgoedhart), first version 2018
# Takes non-tidy, spreadsheet type data as input or tidy format
# Non-tidy data is converted into tidy format
# For tidy data the x and y variables need to be selected
# Raw data is displayed with user-defined visibility (alpha)
# Summary statistics are displayed with user-defined visibility (alpha)
# Inferential statistics (95%CI) can be added
# The 95%CI of the median is determined by resampling (bootstrap)
# A plot and a table with stats are generated
# Colors can be added to the data and/or the stats
# Several colorblind safe palettes are available
# Ordering of the categorial data is 'as is, based on median or alphabetical
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (C) 2018 Joachim Goedhart
# electronic mail address: j #dot# goedhart #at# uva #dot# nl
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
library(shiny)
library(tidyverse)
library(ggbeeswarm)
library(DT)
library(RCurl)
#Uncomment for sinaplot
#library(ggforce)
source("themes.R")
#Function that resamples a vector (with replacement) and calculates the median value
boot_median = function(x) {
median(sample(x, replace = TRUE))
}
geom_mean <- function(x) {
exp(mean(log(x), na.rm=TRUE))
}
i=0
#Number of bootstrap samples
nsteps=1000
#Confidence level
Confidence_Percentage = 95
Confidence_level = Confidence_Percentage/100
alpha=1-Confidence_level
lower_percentile=(1-Confidence_level)/2
upper_percentile=1-((1-Confidence_level)/2)
#Code to generate vectors in R to use these palettes
#From Paul Tol: https://personal.sron.nl/~pault/
Tol_bright <- c('#EE6677', '#228833', '#4477AA', '#CCBB44', '#66CCEE', '#AA3377', '#BBBBBB')
Tol_muted <- c('#88CCEE', '#44AA99', '#117733', '#332288', '#DDCC77', '#999933','#CC6677', '#882255', '#AA4499', '#DDDDDD')
Tol_light <- c('#BBCC33', '#AAAA00', '#77AADD', '#EE8866', '#EEDD88', '#FFAABB', '#99DDFF', '#44BB99', '#DDDDDD')
#From Color Universal Design (CUD): https://jfly.uni-koeln.de/color/
Okabe_Ito <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7", "#000000")
#Read a text file (comma separated values)
df_wide_example <- read.csv("Data_wide_example.csv", na.strings = "")
df_tidy_example <- read.csv("Data_tidy_example.csv", na.strings = "")
#df_wide_example <- data.frame(X=c(1,2,3),Y=c(3,4,5),Z=c(2,5,6))
#df_tidy_example <- data.frame(X=c(1,2,3),Y=c(3,4,5),Z=c(2,5,6))
# Create a reactive object here that we can share between all the sessions.
vals <- reactiveValues(count=0)
###### UI: User interface #########
ui <- fluidPage(
titlePanel("PlotsOfData - Plots all Of the Data"),
sidebarLayout(
sidebarPanel(width=3,
conditionalPanel(
condition = "input.tabs=='Plot'",
radioButtons("jitter_type", "Data offset", choices = list("Quasirandom" = "quasirandom",
#Uncomment for sinaplot "Sinaplot" = "sina",
"Random" = "random",
"None; stripes" = "stripes",
"None (for small n)" = "none"), selected = "quasirandom"),
sliderInput("alphaInput", "Visibility of the data", 0, 1, 0.3),
radioButtons("summaryInput", "Statistics", choices = list("Median" = "median", "Mean" = "mean", "Geometric Mean" = "geom_mean", "Boxplot (minimum n=10)" = "box", "Violin Plot (minimum n=10)" = "violin"), selected = "median"),
checkboxInput(inputId = "add_CI", label = HTML("Add 95% CI <br/> (minimum n=10)"), value = FALSE),
checkboxInput(inputId = "add_SD", label = HTML("Add S.D."), value = FALSE),
conditionalPanel(
condition = "input.add_CI == true && input.summaryInput !='box'",
checkboxInput(inputId = "ugly_errors", label = "Classic error bars", value = FALSE)),
#Uncomment for grey box that indicates range
conditionalPanel(
condition = "input.summaryInput == 'median' || input.summaryInput == 'mean'",
checkboxInput(inputId = "add_bar", label = HTML("Add a box that shows the range"), value = FALSE)),
sliderInput("alphaInput_summ", "Visibility of the statistics", 0, 1, 1),
radioButtons(inputId = "ordered",
label= "Order of the conditions:",
choices = list("As supplied" = "none", "By median value" = "median", "By alphabet/number" = "alphabet"),
selected = "none"),
h4("Plot Layout"),
checkboxInput(inputId = "rotate_plot",
label = "Rotate plot 90 degrees",
value = FALSE),
checkboxInput(inputId = "no_grid",
label = "Remove gridlines",
value = FALSE),
checkboxInput(inputId = "change_scale",
label = "Change scale",
value = FALSE),
conditionalPanel(condition = "input.change_scale == true",
checkboxInput(inputId = "scale_log_10",
label = "Log scale",
value = FALSE),
textInput("range", "Range of values (min,max)", value = "")),
checkboxInput("color_data", "Use color for the data", value=FALSE),
checkboxInput("color_stats", "Use color for the stats", value=FALSE),
conditionalPanel(
condition = "input.color_data == true || input.color_stats == true",
########## Choose color from list
# selectInput("colour_list", "Colour:", choices = ""),
radioButtons("adjustcolors", "Color palette:", choices =
list(
"Standard" = 1,
"Okabe&Ito; CUD" = 6,
"Tol; bright" = 2,
"Tol; muted" = 3,
"Tol; light" = 4,
"User defined"=5),
selected = 6),
conditionalPanel(condition = "input.adjustcolors == 5",
textInput("user_color_list", "Names or hexadecimal codes separated by a comma (applied to conditions in alphabetical order):", value = "turquoise2,#FF2222,lawngreen"),
h5("",
a("Click here for more info on color names",
href = "https://r-charts.com/colors/", target="_blank"))
)),
checkboxInput(inputId = "dark", label = "Dark Theme", value = FALSE),
numericInput("plot_height", "Height (# pixels): ", value = 480),
numericInput("plot_width", "Width (# pixels):", value = 480),
h4("Labels/captions"),
checkboxInput(inputId = "add_title",
label = "Add title",
value = FALSE),
conditionalPanel(
condition = "input.add_title == true",
textInput("title", "Title:", value = "")
),
checkboxInput(inputId = "label_axes",
label = "Change labels",
value = FALSE),
conditionalPanel(
condition = "input.label_axes == true",
textInput("lab_x", "X-axis:", value = ""),
textInput("lab_y", "Y-axis:", value = "")),
checkboxInput(inputId = "adj_fnt_sz",
label = "Change font size",
value = FALSE),
conditionalPanel(
condition = "input.adj_fnt_sz == true",
numericInput("fnt_sz_ttl", "Size axis titles:", value = 24),
numericInput("fnt_sz_ax", "Size axis labels:", value = 18)),
checkboxInput(inputId = "add_description",
label = "Add figure description",
value = FALSE),
NULL
),
conditionalPanel(
condition = "input.tabs=='Data upload'",
h4("Data upload"),
radioButtons(
"data_input", "",
choices =
list("Example 1 (wide format)" = 1,
"Example 2 (tidy format)" = 2,
"Upload file" = 3,
"Paste data" = 4,
"URL (csv files only)" = 5
)
,
selected = 1),
conditionalPanel(
condition = "input.data_input=='1'"
),
conditionalPanel(
condition = "input.data_input=='3'",
fileInput("upload", NULL, multiple = FALSE, accept = c(".xlsx", ".xls", ".txt", ".csv")),
# selectInput("file_type", "Type of file:",
# list(".csv or .txt" = "text",
# ".xls or .xlsx" = "excel"
# ),
# selected = "text"),
# radioButtons(
# "upload_delim", "Delimiter",
# choices =
# list("Comma" = ",",
# "Tab" = "\t",
# "Semicolon" = ";",
# "Space" = " ")),
# selected = ","),
selectInput("upload_delim", label = "Select Delimiter (for text file):", choices =list("Comma" = ",",
"Tab" = "\t",
"Semicolon" = ";",
"Space" = " ")),
selectInput("sheet", label = "Select sheet (for excel workbook):", choices = " ")
# actionButton("submit_datafile_button", "Submit datafile")
),
conditionalPanel(
condition = "input.data_input=='4'",
h5("Paste data below:"),
tags$textarea(id = "data_paste",
placeholder = "Add data here",
rows = 10,
cols = 20, ""),
actionButton("submit_data_button", "Submit data"),
radioButtons(
"text_delim", "Delimiter",
choices =
list("Tab (from Excel)" = "\t",
"Space" = " ",
"Comma" = ",",
"Semicolon" = ";"),
selected = "\t")),
### csv via URL as input
conditionalPanel(
condition = "input.data_input=='5'",
# textInput("URL", "URL", value = "https://zenodo.org/record/2545922/files/FRET-efficiency_mTq2.csv"),
textInput("URL", "URL", value = ""),
NULL
),
checkboxInput(inputId = "tidyInput",
label = "These data are Tidy",
value = FALSE),
# conditionalPanel(
# condition = "input.tidyInput==false", selectInput("data_remove", "Select columns to remove", "", multiple = TRUE)),
#
conditionalPanel(
condition = "input.tidyInput==true",
selectInput("x_var", "Conditions to compare:", choices = ""),
selectInput("y_var", "Variables:", choices = ""),
# selectInput("h_facet", "Separate horizontal:", choices = ""),
# selectInput("v_facet", "Separate vertical:", choices = ""),
NULL
),
conditionalPanel(
condition = "input.tidyInput==false",
selectInput("use_these_conditions", "Select and order:", "", multiple = TRUE),
downloadButton("downloadData", "Download in tidy format (csv)")
),
hr(),
checkboxInput(inputId = "info_data",
label = "Show information on data formats",
value = FALSE),
conditionalPanel(
condition = "input.info_data==true",
img(src = 'Data_format.png', width = '100%'), h5(""), a("Background info for converting wide data to tidy format", href = "http://thenode.biologists.com/converting-excellent-spreadsheets-tidy-data/education/")
)
),
conditionalPanel(
condition = "input.tabs=='About'",
#Session counter: https://gist.github.com/trestletech/9926129
h4("About"), "There are currently",
verbatimTextOutput("count"),
"session(s) connected to this app.",
hr(),
h4("Find our other dataViz apps at:"),a("https://huygens.science.uva.nl/", href = "https://huygens.science.uva.nl/")
),
conditionalPanel(
condition = "input.tabs=='Data Summary'",
h4("Data summary") ,
checkboxGroupInput("stats_select", label = h5("Statistics for table:"),
choices = list("mean", "sd", "sem","95CI mean", "median", "MAD", "IQR", "Q1", "Q3", "95CI median"),
selected = "sem"),
actionButton('select_all1','select all'),
actionButton('deselect_all1','deselect all'),
numericInput("digits", "Digits:", 2, min = 0, max = 5)
# ,
# selectInput("stats_hide2", "Select columns to hide", "", multiple = TRUE, choices=list("mean", "sd", "sem","95CI mean", "median", "MAD", "IQR", "Q1", "Q3", "95CI median")
)
),
mainPanel(
tabsetPanel(id="tabs",
tabPanel("Data upload", h4("Data as provided"),
dataTableOutput("data_uploaded")),
tabPanel("Plot", downloadButton("downloadPlotPDF", "Download pdf-file"),
downloadButton("downloadPlotSVG", "Download svg-file"),
downloadButton("downloadPlotEPS", "Download eps-file"),
downloadButton("downloadPlotPNG", "Download png-file"),
actionButton("settings_copy", icon = icon("clone"),
label = "Clone current setting"),
actionButton("legend_copy", icon = icon("clone"),
label = "Copy Legend"),
div(`data-spy`="affix", `data-offset-top`="10", plotOutput("coolplot", height="100%"),
htmlOutput("LegendText", width="200px", inline =FALSE),
# htmlOutput("HTMLpreset"),
NULL)
),
tabPanel("Data Summary",dataTableOutput('data_summary')
),
tabPanel("About", includeHTML("about.html")
)
)
)
)
)
server <- function(input, output, session) {
isolate(vals$count <- vals$count + 1)
###### DATA INPUT ###################
df_upload <- reactive({
if (input$data_input == 1) {
data <- df_wide_example
} else if (input$data_input == 2) {
data <- df_tidy_example
} else if (input$data_input == 3) {
file_in <- input$upload
# Avoid error message while file is not uploaded yet
if (is.null(input$upload)) {
return(data.frame(x = "Click 'Browse...' to select a datafile or drop file onto 'Browse' button"))
# } else if (input$submit_datafile_button == 0) {
# return(data.frame(x = "Press 'submit datafile' button"))
} else {
#Isolate extenstion and convert to lowercase
filename_split <- strsplit(file_in$datapath, '[.]')[[1]]
fileext <- tolower(filename_split[length(filename_split)])
# observe({print(fileext)})
# isolate({
# data <- read.csv(file=file_in$datapath, sep = input$upload_delim, na.strings=c("",".","NA", "NaN", "#N/A", "#VALUE!"))
if (fileext == "txt" || fileext=="csv") {
data <- read.csv(file=file_in$datapath, sep = input$upload_delim, na.strings=c("",".","NA", "NaN", "#N/A", "#VALUE!"))
updateSelectInput(session, "sheet", choices = " ", selected = " ")
} else if (fileext=="xls" || fileext=="xlsx") {
names <- readxl::excel_sheets(path = input$upload$datapath)
# updateSelectInput(session, "sheet_names", choices = names)
sheet.selected <<- input$sheet
updateSelectInput(session, "sheet", choices = names, selected = sheet.selected)
if (input$sheet %in% names)
{
n <- which(names==input$sheet)
# sheet.selected <<- input$sheet
} else {
n <- 1
#Ensures update and selection of first sheet upon loading the data
updateSelectInput(session, "sheet", choices = names)
}
# names <- excel_sheets(path = input$upload$datapath)
# updateSelectInput(session, "sheet_names", choices = names)
data <- readxl::read_excel(file_in$datapath, sheet = n , na = c("",".","NA", "NaN", "#N/A", "#VALUE!"))
}
# })
}
} else if (input$data_input == 5) {
#Read data from a URL
#This requires RCurl
if(input$URL == "") {
return(data.frame(x = "Enter a full HTML address, for example: https://zenodo.org/record/2545922/files/FRET-efficiency_mTq2.csv"))
} else if (url.exists(input$URL) == FALSE) {
return(data.frame(x = paste("Not a valid URL: ",input$URL)))
} else {data <- read_csv(input$URL)}
#Read the data from textbox
} else if (input$data_input == 4) {
if (input$data_paste == "") {
data <- data.frame(x = "Copy your data into the textbox,
select the appropriate delimiter, and
press 'Submit data'")
} else {
if (input$submit_data_button == 0) {
return(data.frame(x = "Press 'submit data' button"))
} else {
isolate({
data <- read_delim(input$data_paste,
delim = input$text_delim,
col_names = TRUE)
})
}
}
}
# updateSelectInput(session, "data_remove", choices = names(data))
#Replace space and dot of header names by underscore
data <- data %>%
select_all(~gsub("\\s+|\\.", "_", .))
return(data)
})
##### REMOVE SELECTED COLUMNS #########
# df_filtered <- reactive({
#
# if (!is.null(input$use_these_conditions)) {
#
# if (input$tidyInput == TRUE && input$x_var!='none') {
# x_var <- input$x_var
# } else if (input$tidyInput == FALSE) {x_var <- 'Condition'
# } else {return(df_upload_tidy())}
# use_these_conditions <- input$use_these_conditions
#
# observe({print(use_these_conditions)})
#
# #Remove the columns that are selected (using filter() with the exclamation mark preceding the condition)
# # https://dplyr.tidyverse.org/reference/filter.html
# df <- df_upload_tidy() %>% filter(.data[[x_var[[1]]]] %in% !!use_these_conditions)
#
#
# } else {df <- df_upload_tidy()}
#
# })
##### CONVERT TO TIDY DATA ##########
#Need to tidy the data?!
#Untidy data will be converted to long format with two columns named 'Condition' and 'Value'
#The input for "Condition" will be taken from the header, i.e. first row
#Tidy data will be used as supplied
df_upload_tidy <- reactive({
if(input$tidyInput == FALSE ) {
klaas <- df_upload() %>% gather(Condition, Value)
}
else if(input$tidyInput == TRUE ) {
klaas <- df_upload()
}
return(klaas)
})
##### Get Variables from the input ##############
observe({
var_names <- names(df_upload_tidy())
varx_list <- c("none", var_names)
# Get the names of columns that are factors. These can be used for coloring the data with discrete colors
nms_fact <- names(Filter(function(x) is.factor(x) || is.integer(x) ||
is.logical(x) ||
is.character(x),
df_upload_tidy()))
nms_var <- names(Filter(function(x) is.integer(x) ||
is.numeric(x) ||
is.double(x),
df_upload_tidy()))
vary_list <- c("none",nms_var)
facet_list <- c(".",nms_fact)
# updateSelectInput(session, "colour_list", choices = nms_fact)
updateSelectInput(session, "y_var", choices = vary_list)
updateSelectInput(session, "x_var", choices = varx_list)
updateSelectInput(session, "h_facet", choices = facet_list)
updateSelectInput(session, "v_facet", choices = facet_list)
# if (input$add_bar == TRUE) {
# updateSelectInput(session, "alphaInput", min = 0.3)
# }
})
########### When x_var is selected for tidy data, get the list of conditions
####### THIS STILL NEEDS SOME WORK ############
####### when switching back from tidy to non-tidy, the 'use_these_conditions' is not updated
####### I should probably take the df_filtered/df_sorted code from SuperPlotsOfData
observeEvent(input$x_var != 'none' || input$tidyInput == FALSE, {
if (input$x_var != 'none' && input$tidyInput == TRUE) {
filter_column <- input$x_var
if (filter_column == "") {filter_column <- NULL}
koos <- df_upload() %>% select(for_filtering = !!filter_column)
conditions_list <- levels(factor(koos$for_filtering))
# observe(print((conditions_list)))
updateSelectInput(session, "use_these_conditions", choices = conditions_list)
} else if (input$tidyInput == FALSE) {
koos <- df_upload_tidy()
conditions_list <- levels(factor(koos$Condition))
updateSelectInput(session, "use_these_conditions", choices = conditions_list)
}
})
# observeEvent(input$add_bar, {
# showNotification("clicked!", type = "default")
# },ignoreNULL = F)
###### When a bar is added, make sure that the data is still visible
observeEvent(input$add_bar, {
if (input$add_bar==TRUE) {
updateSliderInput(session, "alphaInput", min=0.2, max=1)
} else if (input$add_bar==FALSE) {
updateSliderInput(session, "alphaInput", min=0, max=1)
}
})
observeEvent(input$dark, {
if (input$dark==TRUE) {
updateCheckboxInput(session,"color_data", value=TRUE)
updateCheckboxInput(session,"color_stats", value=TRUE)
updateRadioButtons(session, "adjustcolors", selected=5)
updateTextInput(session, "user_color_list", value = "grey80")
} else if (input$dark==FALSE) {
updateCheckboxInput(session,"color_data", value=FALSE)
updateCheckboxInput(session,"color_stats", value=FALSE)
updateRadioButtons(session, "adjustcolors", selected=6)
}
})
########### GET INPUT VARIABLEs FROM HTML ##############
observe({
############ ?data ################
query <- parseQueryString(session$clientData$url_search)
if (!is.null(query[['data']])) {
presets_data <- query[['data']]
presets_data <- unlist(strsplit(presets_data,";"))
observe(print((presets_data[1])))
# observe(print(("hello")))
updateRadioButtons(session, "data_input", selected = presets_data[1])
updateCheckboxInput(session, "tidyInput", value = presets_data[2])
#To Implement:
#presets_data[3], x_var
#presets_data[4], y_var
#presets_data[5], h_facet
#presets_data[6], v_facet
}
############ ?vis ################
if (!is.null(query[['vis']])) {
presets_vis <- query[['vis']]
presets_vis <- unlist(strsplit(presets_vis,";"))
observe(print((presets_vis)))
#radio, slider, radio, check, slider
updateRadioButtons(session, "jitter_type", selected = presets_vis[1])
updateSliderInput(session, "alphaInput", value = presets_vis[2])
updateRadioButtons(session, "summaryInput", selected = presets_vis[3])
updateCheckboxInput(session, "add_CI", value = presets_vis[4])
updateSliderInput(session, "alphaInput_summ", value = presets_vis[5])
updateRadioButtons(session, "ordered", selected = presets_vis[6])
# updateTabsetPanel(session, "tabs", selected = "Plot")
}
############ ?layout ################
if (!is.null(query[['layout']])) {
presets_layout <- query[['layout']]
presets_layout <- unlist(strsplit(presets_layout,";"))
observe(print((presets_layout)))
updateCheckboxInput(session, "rotate_plot", value = presets_layout[1])
updateCheckboxInput(session, "no_grid", value = (presets_layout[2]))
updateCheckboxInput(session, "change_scale", value = presets_layout[3])
updateCheckboxInput(session, "scale_log_10", value = presets_layout[4])
updateTextInput(session, "range", value= presets_layout[5])
updateCheckboxInput(session, "color_data", value = presets_layout[6])
updateCheckboxInput(session, "color_stats", value = presets_layout[7])
updateRadioButtons(session, "adjustcolors", selected = presets_layout[8])
updateCheckboxInput(session, "add_description", value = presets_layout[9])
if (length(presets_layout)>10) {
updateNumericInput(session, "plot_height", value= presets_layout[10])
updateNumericInput(session, "plot_width", value= presets_layout[11])
}
# updateTabsetPanel(session, "tabs", selected = "Plot")
}
############ ?color ################
if (!is.null(query[['color']])) {
presets_color <- query[['color']]
presets_color <- unlist(strsplit(presets_color,";"))
# updateSelectInput(session, "colour_list", selected = presets_color[1])
updateTextInput(session, "user_color_list", value= presets_color[2])
}
############ ?label ################
if (!is.null(query[['label']])) {
presets_label <- query[['label']]
presets_label <- unlist(strsplit(presets_label,";"))
observe(print((presets_label)))
updateCheckboxInput(session, "add_title", value = presets_label[1])
updateTextInput(session, "title", value= presets_label[2])
updateCheckboxInput(session, "label_axes", value = presets_label[3])
updateTextInput(session, "lab_x", value= presets_label[4])
updateTextInput(session, "lab_y", value= presets_label[5])
updateCheckboxInput(session, "adj_fnt_sz", value = presets_label[6])
updateNumericInput(session, "fnt_sz_ttl", value= presets_label[7])
updateNumericInput(session, "fnt_sz_ax", value= presets_label[8])
updateCheckboxInput(session, "add_description", value = presets_label[9])
}
############ ?url ################
if (!is.null(query[['url']])) {
updateRadioButtons(session, "data_input", selected = 5)
updateTextInput(session, "URL", value= query[['url']])
observe(print((query[['url']])))
updateTabsetPanel(session, "tabs", selected = "Plot")
}
})
########### RENDER URL ##############
output$HTMLpreset <- renderText({
url()
})
######### GENERATE URL with the settings #########
url <- reactive({
base_URL <- paste(sep = "", session$clientData$url_protocol, "//",session$clientData$url_hostname, ":",session$clientData$url_port, session$clientData$url_pathname)
data <- c(input$data_input, input$tidyInput, input$x_var, input$y_var, input$h_facet, input$v_facet)
vis <- c(input$jitter_type, input$alphaInput, input$summaryInput, input$add_CI, input$alphaInput_summ, input$ordered)
layout <- c(input$rotate_plot, input$no_grid, input$change_scale, input$scale_log_10, input$range, input$color_data, input$color_stats,
input$adjustcolors, input$add_description, input$plot_height, input$plot_width)
#Hide the standard list of colors if it is'nt used
if (input$adjustcolors != "5") {
color <- c("", "none")
} else if (input$adjustcolors == "5") {
color <- c("", input$user_color_list)
}
label <- c(input$add_title, input$title, input$label_axes, input$lab_x, input$lab_y, input$adj_fnt_sz, input$fnt_sz_ttl, input$fnt_sz_ax, input$add_description)
#replace FALSE by "" and convert to string with ; as seperator
data <- sub("FALSE", "", data)
data <- paste(data, collapse=";")
data <- paste0("data=", data)
vis <- sub("FALSE", "", vis)
vis <- paste(vis, collapse=";")
vis <- paste0("vis=", vis)
layout <- sub("FALSE", "", layout)
layout <- paste(layout, collapse=";")
layout <- paste0("layout=", layout)
color <- sub("FALSE", "", color)
color <- paste(color, collapse=";")
color <- paste0("color=", color)
label <- sub("FALSE", "", label)
label <- paste(label, collapse=";")
label <- paste0("label=", label)
if (input$data_input == "5") {url <- paste("url=",input$URL,sep="")} else {url <- NULL}
parameters <- paste(data, vis,layout,color,label,url, sep="&")
preset_URL <- paste(base_URL, parameters, sep="?")
observe(print(parameters))
observe(print(preset_URL))
return(preset_URL)
})
############# Pop-up that displays the URL to 'clone' the current settings ################
observeEvent(input$settings_copy , {
showModal(urlModal(url=url(), title = "Use the URL to launch PlotsOfData with the current setting"))
})
observeEvent(input$legend_copy , {
showModal(urlModal(url=Fig_legend(), title = "Legend text"))
})
############# Pop-up appears when a boxplot or violinplot is selected when n<10 ###########
observeEvent(input$summaryInput , {
df_temp <- df_summary_mean()
min_n <- min(df_temp$n)
if (input$summaryInput == "box" && min_n<10) {
showModal(modalDialog(
title = NULL,
"You have selected a boxplot as summary, but one of the conditions has less than 10 datapoints - For n<10 the boxplot is not a suitable summary", easyClose=TRUE, footer = modalButton("Click anywhere to dismiss")
))
} else if (input$summaryInput == "violin" && min_n<10) {
showModal(modalDialog(
title = NULL,
"You have selected a violinplot as summary, but one of the conditions has less than 10 datapoints - For n<10 the violinplot is not a suitable summary", easyClose=TRUE, footer = modalButton("Click anywhere to dismiss")
))
}
})
############# Pop-up appears when the 95%CI is selected when n<10 ###########
observeEvent(input$add_CI , {
df_temp <- df_summary_mean()
min_n <- min(df_temp$n)
if (input$add_CI == TRUE && min_n<10) {
showModal(modalDialog(
title = NULL,
"Confidence Intervals are used to make inferences, but one of the conditions has less than 10 datapoints - It is not recommended to show inferential statistics (CI, sem) for n<10", easyClose=TRUE, footer = modalButton("Click anywhere to dismiss")
))
}
})
######## ORDER the Conditions #######
df_sorted <- reactive({
#######################################
######### FILTER based on SELECTION ###
if (!is.null(input$use_these_conditions)) {
if (input$tidyInput == TRUE && input$x_var!='none') {
x_var <- input$x_var
} else if (input$tidyInput == FALSE) {x_var <- 'Condition'
} else {return(df_selected())}
use_these_conditions <- input$use_these_conditions
observe({print(use_these_conditions)})
#Remove the columns that are selected (using filter() with the exclamation mark preceding the condition)
# https://dplyr.tidyverse.org/reference/filter.html
df <- df_selected() %>% filter(.data[[x_var[[1]]]] %in% !!use_these_conditions)
} else {df <- df_selected()}
klaas <- df
##############################################
######### SORT based on USER INPUT ###########
######### INPUT FROM 'select and order' ######
######### OR: order the condition of plot ####
if(input$ordered == "median") {
# klaas$Condition <- reorder(klaas$Condition, klaas$Value, median, na.rm = TRUE)
klaas <- klaas %>% mutate(Condition = fct_reorder(Condition, Value, median))
} else if (input$ordered == "none") {
if (!is.null(input$use_these_conditions)) {
# Set order based on input
klaas$Condition <- factor(klaas$Condition, levels = input$use_these_conditions)}
else {
klaas$Condition <- factor(klaas$Condition, levels=unique(klaas$Condition))
}
} else if (input$ordered == "alphabet") {
klaas$Condition <- factor(klaas$Condition, levels=unique(sort(klaas$Condition)))
}
return(klaas)
})
######## Extract the data for display & summary stats #######
df_selected <- reactive({
if(input$tidyInput == TRUE ) {
df_temp <- df_upload_tidy()
x_choice <- input$x_var
y_choice <- input$y_var
koos <- df_temp %>% select(Condition = !!x_choice , Value = !!y_choice) %>% filter(!is.na(Value))
# koos$Condition <- factor(koos$Condition)
} else if (input$tidyInput == FALSE ) {
koos <- df_upload_tidy() %>% filter(!is.na(Value))
}
koos <- koos %>% mutate(Condition = as.factor(Condition))
return(koos)
})
#### DISPLAY UPLOADED DATA (as provided) ##################
output$data_uploaded <- renderDataTable(
# observe({ print(input$tidyInput) })
df_upload(),
rownames = FALSE,
options = list(pageLength = 100, autoWidth = FALSE,
lengthMenu = c(10, 100, 1000, 10000)),
editable = FALSE,selection = 'none'
)
########### Caluclate stats for the MEAN ############
df_summary_mean <- reactive({
koos <- df_sorted()
# koos <- df_selected()
# koos$Condition <- factor(koos$Condition)
koos %>%
group_by(Condition) %>%
summarise(n = n(),
mean = mean(Value, na.rm = TRUE),
geom_mean = geom_mean(Value),
# median = median(Value, na.rm = TRUE),
sd = sd(Value, na.rm = TRUE)) %>%
mutate(sem = sd / sqrt(n - 1),
mean_CI_lo = mean + qt((1-Confidence_level)/2, n - 1) * sem,
mean_CI_hi = mean - qt((1-Confidence_level)/2, n - 1) * sem)
})
############ Caluclate stats for the MEDIAN ##########
df_summary_median <- reactive({
kees <- df_sorted()
# kees$Condition <- factor(kees$Condition)
# df_booted <- data.frame(Condition=levels(factor(kees$Condition)), n=tapply(kees$Value, kees$Condition, length), median=tapply(kees$Value, kees$Condition, median))
df_booted <- kees %>%
group_by(Condition) %>%
summarise(
# n= n(),
median= median(Value, na.rm = TRUE),
MAD= mad(Value, na.rm = TRUE, constant=1),
IQR= IQR(Value, na.rm = TRUE),
Q1=quantile(Value, probs=0.25),
Q3=quantile(Value, probs=0.75))
i=0
df_new_medians <- data.frame(Condition=levels(factor(kees$Condition)), resampled_median=tapply(kees$Value, kees$Condition, boot_median))
#Perform the resampling nsteps number of times (typically 1,000-10,000x)
for (i in 1:nsteps) {
#Caclulate the median from a boostrapped sample (resampled_median) and add to the dataframe
df_boostrapped_median <- data.frame(Condition=levels(factor(kees$Condition)), resampled_median=tapply(kees$Value, kees$Condition, boot_median))
#Add the new median to a datafram that collects all the resampled median values
df_new_medians <- bind_rows(df_new_medians, df_boostrapped_median)
}
df_booted$median_CI_lo <- tapply(df_new_medians$resampled_median, df_new_medians$Condition, quantile, probs=lower_percentile)
df_booted$median_CI_hi <- tapply(df_new_medians$resampled_median, df_new_medians$Condition, quantile, probs=upper_percentile)
# observe({ print(df_booted) })
return(df_booted)
})
######### DEFINE DOWNLOAD BUTTONS ###########
##### Set width and height of the plot area
width <- reactive ({ input$plot_width })
height <- reactive ({ input$plot_height })
output$downloadPlotPDF <- downloadHandler(
filename <- function() {
paste("PlotsOfData_", Sys.time(), ".pdf", sep = "")
},
content <- function(file) {
pdf(file, width = input$plot_width/72, height = input$plot_height/72)
plot(plotdata())
dev.off()
},
contentType = "application/pdf" # MIME type of the image
)
output$downloadPlotSVG <- downloadHandler(
filename <- function() {
paste("PlotsOfData_", Sys.time(), ".svg", sep = "")
},
content <- function(file) {
svg(file, width = input$plot_width/72, height = input$plot_height/72)
plot(plotdata())
dev.off()
},
contentType = "application/svg" # MIME type of the image