/
ggsurvplot.R
1081 lines (981 loc) · 44 KB
/
ggsurvplot.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
#' @include utilities.R theme_classic2.R surv_summary.R
#' @importFrom methods is
#' @importFrom stats pchisq
#' @importFrom survMisc ten comp
#' @importFrom utils capture.output
NULL
#'Drawing Survival Curves Using ggplot2
#'@description Drawing survival curves using ggplot2
#'@param fit an object of class survfit.
#'@param data a dataset used to fit survival curves. If not supplied then data
#' will be extracted from 'fit' object.
#'@param fun an arbitrary function defining a transformation of the survival
#' curve. Often used transformations can be specified with a character
#' argument: "event" plots cumulative events (f(y) = 1-y), "cumhaz" plots the
#' cumulative hazard function (f(y) = -log(y)), and "pct" for survival
#' probability in percentage.
#'@param surv.scale scale transformation of survival curves. Allowed values are
#' "default" or "percent".
#'@param color color to be used for the survival curves. This argument is
#' ignored when the number of strata (groups > 1). In this case, use the
#' argument palette.
#'@param palette the color palette to be used. Allowed values include "hue" for
#' the default hue color scale; "grey" for grey color palettes; brewer palettes
#' e.g. "RdBu", "Blues", ...; or custom color palette e.g. c("blue", "red").
#' See details section for more information.
#'@param linetype line types. Allowed values includes i) "strata" for changing
#' linetypes by strata (i.e. groups); ii) a numeric vector (e.g., c(1, 2)) or a
#' character vector c("solid", "dashed").
#'@param break.time.by numeric value controlling time axis breaks. Default value
#' is NULL.
#'@param conf.int logical value. If TRUE, plots confidence interval.
#'@param conf.int.fill fill color to be used for confidence interval.
#'@param conf.int.style confidence interval style. Allowed values include
#' c("ribbon", "step").
#'@param censor logical value. If TRUE, censors will be drawn.
#'@param pval logical value. If TRUE, the p-value is added on the plot.
#'@param pval.size numeric value specifying the p-value text size. Default is 5.
#'@param pval.coord numeric vector, of length 2, specifying the x and y
#' coordinates of the p-value. Default values are NULL.
#'@param main,submain,caption,xlab,ylab main title, subtitle, caption and axis
#' labels
#'@param xlim,ylim x and y axis limits e.g. xlim = c(0, 1000), ylim = c(0, 1).
#'@param legend character specifying legend position. Allowed values are one of
#' c("top", "bottom", "left", "right", "none"). Default is "top" side position.
#' to remove the legend use legend = "none". Legend position can be also
#' specified using a numeric vector c(x, y); see details section.
#'@param legend.title legend title.
#'@param legend.labs character vector specifying legend labels. Used to replace
#' the names of the strata from the fit. Should be given in the same order as
#' those strata.
#'@param risk.table Allowed values include: \itemize{ \item TRUE or FALSE
#' specifying whether to show or not the risk table. Default is FALSE. \item
#' "absolute" or "percentage": to show the \bold{absolute number} and the
#' \bold{percentage} of subjects at risk by time, respectively. Use "abs_pct"
#' to show both absolute number and percentage.}
#'
#'@param risk.table.title The title to be used for the risk table.
#'@param risk.table.col color to be used for risk table. Default value is
#' "black". If you want to color by strata (i.e. groups), use risk.table.col =
#' "strata".
#'@param risk.table.fontsize,fontsize font size to be used for the risk table and the cumulative events table.
#'@param risk.table.y.text logical. Default is TRUE. If FALSE, risk table y axis
#' tick labels will be hidden.
#'@param risk.table.y.text.col logical. Default value is FALSE. If TRUE, risk
#' table tick labels will be colored by strata.
#'@param risk.table.height the height of the risk table on the grid. Increase
#' the value when you have many strata. Default is 0.25. Ignored when
#' risk.table = FALSE.
#'@param surv.plot.height the height of the survival plot on the grid. Default
#' is 0.75. Ignored when risk.table = FALSE. \code{1-risk.table.height -
#' ncensor.plot.height} when \code{risk.table = TRUE} and \code{ncensor.plot =
#' TRUE}
#'@param ncensor.plot logical value. If TRUE, the number of censored subjects at
#' time t is plotted. Default is FALSE.
#'@param ncensor.plot.title The title to be used for the censor plot. Used when
#' \code{ncensor.plot = TRUE}.
#'@param ncensor.plot.height The height of the censor plot. Used when
#' \code{ncensor.plot = TRUE}.
#'@param cumevents logical value specifying whether to show or not the table of
#' the cumulative number of events. Default is FALSE.
#'@param cumevents.title The title to be used for the cumulative events table.
#'@param cumevents.col color to be used for cumulative events table. Default value is
#' "black". If you want to color by strata (i.e. groups), use cumevents.col =
#' "strata".
#'@param cumevents.y.text logical. Default is TRUE. If FALSE, the y axis
#' tick labels of the cumulative events table will be hidden.
#'@param cumevents.y.text.col logical. Default value is FALSE. If TRUE,
#' the y tick labels of the cumulative events will be colored by strata.
#'@param cumevents.height the height of the cumulative events table on the grid. Default is 0.25. Ignored when
#' cumevents = FALSE.
#'@param surv.median.line character vector for drawing a horizontal/vertical
#' line at median survival. Allowed values include one of c("none", "hv", "h",
#' "v"). v: vertical, h:horizontal.
#'@param ggtheme function, ggplot2 theme name. Default value is
#' \link{theme_classic2}. Allowed values include ggplot2 official themes: see
#' \code{\link[ggplot2]{theme}}.
#'@param ... other arguments to be passed i) to ggplot2 geom_*() functions such
#' as linetype, size, ii) or to the function ggpubr::ggpar() for customizing
#' the plots. See details section.
#'@param log.rank.weights The name for the type of weights to be used in
#' computing the p-value for log-rank test. By default \code{survdiff} is used
#' to calculate regular log-rank test (with weights == 1). A user can specify
#' \code{"1", "n", "sqrtN", "S1", "S2", "FH"} to use weights specified in
#' \link[survMisc]{comp}, so that weight correspond to the test as : 1 -
#' log-rank, n - Gehan-Breslow (generalized Wilcoxon), sqrtN - Tarone-Ware, S1
#' - Peto-Peto's modified survival estimate, S2 - modified Peto-Peto (by
#' Andersen), FH - Fleming-Harrington(p=1, q=1).
#'@param pval.method whether to add a text with the test name used for
#' calculating the pvalue, that corresponds to survival curves' comparison -
#' used only when \code{pval=TRUE}
#'@param pval.method.size the same as \code{pval.size} but for displaying
#' \code{log.rank.weights} name
#'@param pval.method.coord the same as \code{pval.coord} but for displaying
#' \code{log.rank.weights} name
#'@details \strong{legend position}: The argument \strong{legend} can be also a
#' numeric vector c(x,y). In this case it is possible to position the legend
#' inside the plotting area. x and y are the coordinates of the legend box.
#' Their values should be between 0 and 1. c(0,0) corresponds to the "bottom
#' left" and c(1,1) corresponds to the "top right" position. For instance use
#' legend = c(0.8, 0.2).\cr\cr \strong{Color palettes}: The argument
#' \strong{palette} can be used to specify the color to be used for each group.
#' By default, the first color in the palette is used to color the first level
#' of the factor variable. This default behavior can be changed by assigning
#' correctly a named vector. That is, the names of colors should match the
#' strata names as generated by the \code{ggsurvplot()} function in the
#' legend.\cr\cr \strong{Customizing the plots}: The plot can be easily
#' customized using additional arguments to be passed to the function ggpar().
#' Read ?ggpubr::ggpar. These arguments include
#' \emph{font.main,font.submain,font.caption,font.x,font.y,font.tickslab,font.legend}:
#' a vector of length 3 indicating respectively the size (e.g.: 14), the style
#' (e.g.: "plain", "bold", "italic", "bold.italic") and the color (e.g.: "red")
#' of main title, subtitle, caption, xlab and ylab and axis tick labels,
#' respectively. For example \emph{font.x = c(14, "bold", "red")}. Use font.x
#' = 14, to change only font size; or use font.x = "bold", to change only font
#' face.
#'
#'@return return an object of class ggsurvplot which is list containing two
#' ggplot objects, including: \itemize{ \item plot: the survival plot \item
#' table: the number at risk table per time }
#'
#'@author Alboukadel Kassambara, \email{alboukadel.kassambara@@gmail.com}
#' @examples
#'
#'#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#'# Example 1: Survival curves with two groups
#'#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#'
#'# Fit survival curves
#'#++++++++++++++++++++++++++++++++++++
#'require("survival")
#'fit<- survfit(Surv(time, status) ~ sex, data = lung)
#'
#'# Drawing survival curves
#'ggsurvplot(fit, data = lung)
#'
#'# Change font size, style and color
#'#++++++++++++++++++++++++++++++++++++
#'\dontrun{
#' # Change font size, style and color at the same time
#' ggsurvplot(fit, data = lung, main = "Survival curve",
#' font.main = c(16, "bold", "darkblue"),
#' font.x = c(14, "bold.italic", "red"),
#' font.y = c(14, "bold.italic", "darkred"),
#' font.tickslab = c(12, "plain", "darkgreen"))
#'}
#'
#'# Legend: title, labels and position
#'#++++++++++++++++++++++++++++++++++++
#'
#'# Change the legend title and labels
#'ggsurvplot(fit, data = lung, legend = "bottom",
#' legend.title = "Sex",
#' legend.labs = c("Male", "Female"))
#'
#'# Specify legend position by its coordinates
#'ggsurvplot(fit, data = lung, legend = c(0.2, 0.2))
#'
#'
#'# format
#'#++++++++++++++++++++++++++++++++++++
#'# change line size --> 1
#'# Change line types by groups (i.e. "strata")
#'# and change color palette
#'ggsurvplot(fit, data = lung, size = 1, # change line size
#' linetype = "strata", # change line type by groups
#' break.time.by = 250, # break time axis by 250
#' palette = c("#E7B800", "#2E9FDF"), # custom color palette
#' conf.int = TRUE, # Add confidence interval
#' pval = TRUE # Add p-value
#')
#'
#'# Use brewer color palette "Dark2"
#'# Add risk table
#'ggsurvplot(fit, data = lung, linetype = "strata",
#' conf.int = TRUE, pval = TRUE,
#' palette = "Dark2", risk.table = TRUE)
#'
#'
#'# Change color, linetype by strata, risk.table color by strata
#'ggsurvplot(fit, data = lung,
#' pval = TRUE, conf.int = TRUE,
#' risk.table = TRUE, # Add risk table
#' risk.table.col = "strata", # Change risk table color by groups
#' linetype = "strata", # Change line type by groups
#' ggtheme = theme_bw(), # Change ggplot2 theme
#' palette = c("#E7B800", "#2E9FDF"))
#'
#'
#'#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#'# Example 3: Survival curve with multiple group
#'#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#'
#'# Fit (complexe) survival curves
#'#++++++++++++++++++++++++++++++++++++
#' \dontrun{
#'require("survival")
#'fit2 <- survfit( Surv(time, status) ~ rx + adhere,
#' data = colon )
#'
#'# Visualize
#'#++++++++++++++++++++++++++++++++++++
#'
#'# Visualize: add p-value, chang y limits
#'# change color using brewer palette
#'# Adjust risk table and survival plot heights
#'ggsurvplot(fit2, data = colon, pval = TRUE,
#' break.time.by = 400,
#' risk.table = TRUE,
#' risk.table.col = "strata",
#' risk.table.height = 0.5, # Useful when you have multiple groups
#' palette = "Dark2")
#'}
#'
#'
#'#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#'# Example 4: Facet ggsurvplot() output by
#' # a combination of factors
#'#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#'
#'# Fit (complexe) survival curves
#'#++++++++++++++++++++++++++++++++++++
#' \dontrun{
#'require("survival")
#'fit3 <- survfit( Surv(time, status) ~ sex + rx + adhere,
#' data = colon )
#'
#'# Visualize
#'#++++++++++++++++++++++++++++++++++++
#' ggsurv <- ggsurvplot(fit3, data = colon,
#' fun = "cumhaz", conf.int = TRUE,
#' risk.table = TRUE, risk.table.col="strata",
#' ggtheme = theme_bw())
#'
#' # Faceting survival curves
#' curv_facet <- ggsurv$plot + facet_grid(rx ~ adhere)
#' curv_facet
#'
#' # Faceting risk tables:
#' # Generate risk table for each facet plot item
#' ggsurv$table + facet_grid(rx ~ adhere, scales = "free")+
#' theme(legend.position = "none")
#'
#' # Generate risk table for each facet columns
#' tbl_facet <- ggsurv$table + facet_grid(.~ adhere, scales = "free")
#' tbl_facet + theme(legend.position = "none")
#'
#' # Arrange faceted survival curves and risk tables
#' g2 <- ggplotGrob(curv_facet)
#' g3 <- ggplotGrob(tbl_facet)
#' min_ncol <- min(ncol(g2), ncol(g3))
#' g <- gridExtra::rbind.gtable(g2[, 1:min_ncol], g3[, 1:min_ncol], size="last")
#' g$widths <- grid::unit.pmax(g2$widths, g3$widths)
#' grid::grid.newpage()
#' grid::grid.draw(g)
#'
#'
#'
#'
#'}
#'
#'#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#'# Example 5: Playing with fonts and texts
#'#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#'
#'ggsurvplot(fit, data = lung,
#' main = "Survival curves", submain = "Based on Kaplan-Meier estimates",
#' caption = "created with survminer",
#' font.main = c(16, "bold", "darkblue"),
#' font.submain = c(15, "bold.italic", "purple"),
#' font.caption = c(14, "plain", "orange"),
#' font.x = c(14, "bold.italic", "red"),
#' font.y = c(14, "bold.italic", "darkred"),
#' font.tickslab = c(12, "plain", "darkgreen"),
#' ########## risk table #########,
#' risk.table = TRUE,
#' risk.table.title = "Note the risk set sizes",
#' risk.table.subtitle = "and remember about censoring.",
#' risk.table.caption = "source code: website.com",
#' risk.table.height = 0.35,
#' ######### ncensor plot #######
#' ncensor.plot = TRUE,
#' ncensor.plot.title = "Number of censorings",
#' ncensor.plot.subtitle = "over the time.",
#' ncensor.plot.caption = "data available at data.com",
#' ncensor.plot.height = 0.35)
#'
#' ggsurvplot(fit, data = lung,
#' main = "Survival curves", submain = "Based on Kaplan-Meier estimates",
#' caption = "created with survminer",
#' font.main = c(16, "bold", "darkblue"),
#' font.submain = c(15, "bold.italic", "purple"),
#' font.caption = c(14, "plain", "orange"),
#' font.x = c(14, "bold.italic", "red"),
#' font.y = c(14, "bold.italic", "darkred"),
#' font.tickslab = c(12, "plain", "darkgreen"),
#' ########## risk table #########,
#' risk.table = TRUE,
#' risk.table.title = "Note the risk set sizes",
#' risk.table.subtitle = "and remember about censoring.",
#' risk.table.caption = "source code: website.com",
#' risk.table.height = 0.35,
#' font.risk.table.title = c(13, "bold.italic", "green"),
#' font.risk.table.subtitle = c(15, "bold", "pink"),
#' font.risk.table.caption = c(11, "plain", "darkgreen"),
#' font.risk.table.x = c(8, "bold.italic", "orange"),
#' font.risk.table.y = c(11, "bold.italic", "darkgreen"),
#' font.risk.table.tickslab = c(9, "bold", "red"),
#' ######### ncensor plot ###################
#' ncensor.plot = TRUE,
#' ncensor.plot.title = "Number of censorings",
#' ncensor.plot.subtitle = "over the time.",
#' ncensor.plot.caption = "data available at data.com",
#' ncensor.plot.height = 0.35,
#' font.ncensor.plot.title = c(13, "bold.italic", "green"),
#' font.ncensor.plot.subtitle = c(15, "bold", "pink"),
#' font.ncensor.plot.caption = c(11, "plain", "darkgreen"),
#' font.ncensor.plot.x = c(8, "bold.italic", "orange"),
#' font.ncensor.plot.y = c(11, "bold.italic", "darkgreen"),
#' font.ncensor.plot.tickslab = c(9, "bold", "red"))
#'
#'
#'
#'@describeIn ggsurvplot Draws survival curves using ggplot2.
#'@export
ggsurvplot <- function(fit, data = NULL, fun = NULL,
color = NULL, palette = "hue", linetype = 1, break.time.by = NULL,
surv.scale = c("default", "percent"),
conf.int = FALSE, conf.int.fill = "gray", conf.int.style = "ribbon",
censor = TRUE,
pval = FALSE, pval.size = 5, pval.coord = c(NULL, NULL),
pval.method = FALSE, pval.method.size = pval.size, pval.method.coord = c(NULL, NULL),
log.rank.weights = c("survdiff", "1", "n", "sqrtN", "S1", "S2", "FH_p=1_q=1"),
main = NULL, submain = NULL, caption = NULL, xlab = "Time", ylab = "Survival probability",
xlim = NULL, ylim = NULL,
legend = c("top", "bottom", "left", "right", "none"),
legend.title = "Strata", legend.labs = NULL,
#font.legend = c(10, "plain", "black"),
risk.table = FALSE, risk.table.title = NULL,
risk.table.col = "black", risk.table.fontsize = 4.5, fontsize = 4.5,
risk.table.y.text = TRUE,
risk.table.y.text.col = TRUE,
risk.table.height = 0.25, surv.plot.height = 0.75, ncensor.plot.height = 0.25, cumevents.height = 0.25,
ncensor.plot = FALSE, ncensor.plot.title = NULL,
cumevents = FALSE, cumevents.col = "black", cumevents.title = "Cumulative number of events",
cumevents.y.text = TRUE, cumevents.y.text.col = TRUE,
surv.median.line = c("none", "hv", "h", "v"),
ggtheme = theme_survminer(),
...
){
if(!inherits(fit, "survfit"))
stop("Can't handle an object of class ", class(fit))
size <- ifelse(is.null(list(...)$size), 1, list(...)$size)
if(is.null(xlim)) xlim <- c(0, max(fit$time))
if(is.null(ylim) & is.null(fun)) ylim <- c(0, 1)
if(!is(legend, "numeric")) legend <- match.arg(legend)
surv.median.line <- match.arg(surv.median.line)
stopifnot(log.rank.weights %in% c("survdiff", "1", "n", "sqrtN", "S1", "S2","FH_p=1_q=1"))
log.rank.weights <- match.arg(log.rank.weights)
# Adapt ylab value according to the value of the argument fun
ylab <- .check_ylab(ylab, fun)
# Check and get linetypes
lty <- .get_lty(linetype)
linetype <- lty$lty
linetype.manual <- lty$lty.manual
# Check legend
.check_legend_labs(fit, legend.labs)
# risk.table argument
risktable <- .parse_risk_table_arg(risk.table)
risk.table <- risktable$display
risk.table.type <- risktable$type
if(is.null(risk.table.title)){
if(risk.table.type == "percentage") risk.table.title = "Percentage at risk by time"
else if(risk.table.type == "abs_pct") risk.table.title = "Number at risk by time: n (%)"
else risk.table.title = "Number at risk by time"
}
extra.params <- list(...)
# Data
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# data used to compute survfit
data <- .get_data(fit, data = data)
# Data for survival plot
d <- surv_summary(fit, data = data)
# Number of strata and strata names
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
.strata <- d$strata
# Multiple groups
if (!is.null(.strata)){
strata_names <- levels(.strata)
n.strata <- length(strata_names)
if(is.null(legend.labs)) legend.labs <- strata_names
if(missing(color)) color <- "strata"
}
# One group
else{
n.strata <- 1
if (is.null(legend.labs)) {
.strata <- as.factor(rep("All", nrow(d)))
legend.labs <- strata_names <- "All"
}
else {
.strata <- as.factor(rep(legend.labs, nrow(d)))
strata_names <- legend.labs
}
if(missing(conf.int)) conf.int = TRUE
if(missing(color)) color <- "black"
}
d$strata <- .strata
# Connect surv data to the origin for plotting
# time = 0, surv = 1
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
d <- .connect2origin(d, fit, data)
# Transformation of the survival curve
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
d <- .apply_surv_func(d, fun = fun)
# Scale transformation
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
surv.scale <- match.arg(surv.scale)
scale_labels <- ggplot2::waiver()
if (surv.scale == "percent") scale_labels <- scales::percent
# Drawing survival curves
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
d$strata <- factor(d$strata, levels = strata_names, labels = legend.labs)
d <- d[order(d$strata), , drop = FALSE]
surv.color <- ifelse(n.strata > 1, "strata", color)
p <- ggplot2::ggplot(d, ggplot2::aes_string("time", "surv")) +
ggpubr::geom_exec(ggplot2::geom_step, data = d, size = size, color = surv.color, linetype = linetype, ...) +
ggplot2::scale_y_continuous(labels = scale_labels, limits = ylim) +
ggplot2::coord_cartesian(xlim = xlim)+
ggtheme
# if palette != hue
if(!("hue" %in% palette)){
p <- p + .ggcolor(palette)+
.ggfill(palette)
}
if(is.null(break.time.by)) times <- .get_x_major_breaks(p)
else times <- seq(0, max(c(fit$time, xlim)), by = break.time.by)
p <- p + ggplot2::scale_x_continuous(breaks = times)
# Add confidence interval
if(conf.int){
if(missing(conf.int.fill)) conf.int.fill <- surv.color
if(conf.int.style == "ribbon"){
p <- p + .geom_exec(.geom_confint, data = d,
ymin = "lower", ymax = "upper",
fill = conf.int.fill, alpha = 0.3, na.rm = TRUE)
}
else if(conf.int.style == "step"){
p <- p + .geom_exec(ggplot2::geom_step, data = d,
y = "lower", linetype = "dashed",
color = surv.color, na.rm = TRUE)+
.geom_exec(ggplot2::geom_step, data = d,
y = "upper", linetype = "dashed",
color = surv.color, na.rm = TRUE)
}
}
# Add cencored
if (censor & any(d$n.censor >= 1)) {
p <- p + .geom_exec(ggplot2::geom_point, data = d[d$n.censor > 0, , drop = FALSE],
colour = surv.color, size = size*4.5, shape = "+")
}
# Add pvalue
if(pval & !is.null(fit$strata)){
pval <- .get_pvalue(fit, method = log.rank.weights, data = data)
pvaltxt <- ifelse(pval$val < 1e-04, "p < 0.0001",
paste("p =", signif(pval$val, 2)))
pval.x <- ifelse(is.null(pval.coord[1]), 0.1*max(fit$time), pval.coord[1])
pval.y <- ifelse(is.null(pval.coord[2]), 0.2, pval.coord[2])
p <- p + ggplot2::annotate("text", x = pval.x, y = pval.y,
label = pvaltxt, size = pval.size)
if(pval.method){
pvalmethod <- pval$method
pval.method.x <- ifelse(is.null(pval.method.coord[1]), 0.1*max(fit$time), pval.method.coord[1])
pval.method.y <- ifelse(is.null(pval.method.coord[2]), 0.3, pval.method.coord[2])
p <- p + ggplot2::annotate("text", x = pval.method.x, y = pval.method.y,
label = pvalmethod, size = pval.method.size)
}
}
# Drawing a horizontal line at 50% survival
#if(surv.scale == "percent") fun <- "pct"
if(surv.median.line %in% c("hv", "h", "v"))
p <- .add_surv_median(p, fit, type = surv.median.line, fun = fun, data = data)
# Axis limits
p <- p + ggplot2::expand_limits(x = 0, y = 0)
# Axis label and legend title
lty.leg.title <- ifelse(linetype == "strata", legend.title, linetype)
p <- p + ggplot2::labs(x = xlab, y = ylab, title = main, subtitle = submain, caption = caption,
color = legend.title, fill = legend.title,
linetype = lty.leg.title
)
p <- .set_general_gpar(p, legend = legend, ...) # general graphical parameters
if(!is.null(linetype.manual)) p <- p + scale_linetype_manual(values = linetype.manual)
# Add risk table
if(risk.table){
risktable <- .risk_table_plot(fit, data = data, times = times,
xlim = xlim, legend.labs = legend.labs,
risk.table.col = risk.table.col, palette = palette,
ggtheme = ggtheme, risk.table.fontsize = risk.table.fontsize,
risk.table.title = risk.table.title,
risk.table.y.text = risk.table.y.text,
font.tickslab = extra.params$font.risk.table.tickslab,
type = risk.table.type
)
risktable <- .set_general_gpar(risktable, legend = "none", ...) # general graphical parameters
risktable <- .set_risktable_gpar(risktable, legend = "none", ...) # specific graphical params
risktable <- risktable + labs(x = xlab, y = legend.title)
if(!risk.table.y.text)
risktable <- risktable + theme(axis.text.y = element_text(size = 50, vjust = 0.35),
axis.ticks.y = element_blank())
# risktable <-.labs(risktable, xlab = xlab, ylab = legend.title)
risktable <- risktable + ggplot2::labs(color = legend.title, shape = legend.title)
if("left" %in% legend) risktable <- risktable + ggplot2::theme(legend.position = legend)
# color risk.table ticks by strata
if(risk.table.y.text.col){
g <- ggplot2::ggplot_build(p)
cols <- unlist(unique(g$data[[1]]["colour"]))
if(length(cols)==1) cols <- rep(cols, length(legend.labs))
names(cols) <- legend.labs # Give every color an appropriate name
risktable <- risktable + ggplot2::theme(axis.text.y = ggplot2::element_text(colour = rev(cols)))
}
res <- list(plot = p, table = risktable)
}
else res <- list(plot = p)
if(cumevents){
res$cumevents <- ggcumevents (fit, data = data, color = cumevents.col,
palette = palette, break.time.by = break.time.by,
xlim = xlim, title = cumevents.title,
legend = legend, legend.title = legend.title, legend.labs = legend.labs,
y.text = cumevents.y.text, y.text.col = cumevents.y.text,
fontsize = fontsize, ggtheme = ggtheme, ...)
}
# Plot of censored subjects
#%%%%%%%%%%%%%%%%%%%%%%%%%%%
if(ncensor.plot){
ncensor_plot <- ggplot(d, aes_string("time", "n.censor")) +
.geom_exec(geom_bar, d, color = surv.color, fill = surv.color,
stat = "identity", position = "dodge")+
coord_cartesian(xlim = xlim)+
scale_x_continuous(breaks = times)+
scale_y_continuous(breaks = sort(unique(d$n.censor))) +
ggtheme
# if palette != hue
if(!("hue" %in% palette)){
ncensor_plot <- ncensor_plot +
.ggcolor(palette, breaks = strata_names, labels = legend.labs)+
.ggfill(palette, breaks = strata_names, labels = legend.labs)
}
ncensor_plot <- .set_general_gpar(ncensor_plot, legend = "none", ...) # general graphical parameters
ncensor_plot <- .set_ncensorplot_gpar(ncensor_plot, legend = "none", ...) # specific graphical params
ncensor_plot <- ncensor_plot + ggplot2::labs(color = legend.title, fill = legend.title,
x = xlab, y = "n.censor", title = ncensor.plot.title)
if("left" %in% legend) ncensor_plot <- ncensor_plot + ggplot2::theme(legend.position = legend)
res$ncensor.plot <- ncensor_plot
}
heights <- list(
plot = surv.plot.height,
table = ifelse(risk.table, risk.table.height, 0),
ncensor.plot = ifelse(ncensor.plot, ncensor.plot.height, 0),
cumevents = ifelse(cumevents, cumevents.height, 0)
)
class(res) <- c("ggsurvplot", "ggsurv", "list")
attr(res, "heights") <- heights
attr(res, "legend.labs") <- legend.labs
attr(res, "surv.plot.height") <- surv.plot.height
attr(res, "risk.table.height") <- risk.table.height
attr(res, "ncensor.plot.height") <- ncensor.plot.height
attr(res, "risk.table.y.text") <- risk.table.y.text
attr(res, "risk.table.y.text.col") <- risk.table.y.text.col
attr(res, "cumevents.y.text") <- cumevents.y.text
attr(res, "cumevents.y.text.col") <- cumevents.y.text.col
res
# ggpubr::ggpar(res, palette = palette)
}
#' @param x an object of class ggsurvplot
#' @method print ggsurvplot
#' @param newpage open a new page. See \code{\link{grid.arrange}}
#' @rdname ggsurvplot
#' @export
print.ggsurvplot <- function(x, surv.plot.height = NULL, risk.table.height = NULL, ncensor.plot.height = NULL, newpage = TRUE, ...){
res <- .build_ggsurvplot(x = x, surv.plot.height = surv.plot.height,
risk.table.height = risk.table.height,
ncensor.plot.height = ncensor.plot.height)
if(newpage) grid::grid.newpage()
grid::grid.draw(res)
}
# Build ggsurvplot for printing
.build_ggsurvplot <- function(x, surv.plot.height = NULL,
risk.table.height = NULL, ncensor.plot.height = NULL,
cumevents.height = NULL, ...)
{
if(!inherits(x, "ggsurvplot"))
stop("An object of class ggsurvplot is required.")
heights <- attr(x, "heights")
params <- attr(x, "call")
# Update heights
if(!is.null(surv.plot.height)) heights$plot <- surv.plot.height
if(!is.null(risk.table.height)) heights$table <- risk.table.height
if(!is.null(ncensor.plot.height)) heights$ncensor.plot <- ncensor.plot.height
if(!is.null(cumevents.height)) heights$cumevents <- cumevents.height
heights$plot <- 1 - heights$table - heights$ncensor.plot - heights$cumevents
# Extract strata colors for survival curves
legend.labs <- attr(x, "legend.labs")
g <- ggplot_build(x$plot)
cols <- unlist(unique(g$data[[1]]["colour"]))
if(length(cols)==1) cols <- rep(cols, length(legend.labs))
names(cols) <- legend.labs # Give every color an appropriate name
if(!is.null(x$table)){
# Hide legende: don't use theme(legend.position = "none") because awkward legend when position = "left"
x$table <- .hide_legend(x$table)
risk.table.y.text <- attr(x, 'risk.table.y.text')
if(!risk.table.y.text)
x$table <- x$table + theme(axis.text.y = element_text(size = 50, vjust = 0.35),
axis.ticks.y = element_blank())
# Make sure that risk.table.y.text.col will be the same as the plot legend colors
risk.table.y.text.col <- attr(x, 'risk.table.y.text.col')
if(risk.table.y.text.col)
x$table <- x$table + ggplot2::theme(axis.text.y = ggplot2::element_text(colour = rev(cols)))
}
if(!is.null(x$cumevents)){
x$cumevents <- .hide_legend(x$cumevents)
cumevents.y.text <- attr(x, 'cumevents.y.text')
if(!cumevents.y.text)
x$cumevents <- x$cumevents + theme(axis.text.y = element_text(size = 50, vjust = 0.35),
axis.ticks.y = element_blank())
# Make sure that y.text.col will be the same as the plot legend colors
cumevents.y.text.col <- attr(x, 'cumevents.y.text.col')
if(cumevents.y.text.col)
x$cumevents <- x$cumevents + ggplot2::theme(axis.text.y = ggplot2::element_text(colour = rev(cols)))
}
if(!is.null(x$ncensor.plot)) x$ncensor.plot <- x$ncensor.plot + theme (legend.position = "none")
nplot <- length(x)
if(is.null(x$table) & is.null(x$ncensor.plot) & is.null(x$cumevents)) return(x$plot)
heights <- unlist(heights)[names(x)] # get the height of each component in x
plots <- x
grobs <- widths <- list()
for (i in 1:length(plots)) {
grobs[[i]] <- ggplotGrob(plots[[i]])
widths[[i]] <- grobs[[i]]$widths[2:5]
}
maxwidth <- do.call(grid::unit.pmax, widths)
for (i in 1:length(grobs)) {
grobs[[i]]$widths[2:5] <- as.list(maxwidth)
}
res <- gridExtra::arrangeGrob(grobs = grobs, nrow = nplot, heights = unlist(heights))
return(res)
}
.hide_legend <- function(p){
p <- p + theme(legend.key.height = NULL, legend.key.width = NULL,
legend.key = element_rect(colour = NA, fill = NA),
legend.text = element_text(colour = NA),
legend.title = element_text(colour = NA)) +
guides(color = FALSE)
}
# Function defining a transformation of the survival curve
# ++++++++++++++++++++++++++++++++++++++++++++++
# see ?survival::plot.survfit
# d: data frame containing the column surv, upper and lower
# fun the function
.apply_surv_func <- function(d, fun = NULL){
if (!is.null(fun)) {
if (is.character(fun)) {
fun <- switch(fun, log = function(y) log(y),
event = function(y) 1 - y,
cumhaz = function(y) -log(y),
cloglog = function(y) log(-log(y)),
pct = function(y) y * 100,
logpct = function(y) 100 * y,
identity = function(y) y,
stop("Unrecognized survival function argument"))
}
else if (!is.function(fun)) {
stop("Invalid 'fun' argument")
}
d$surv <- fun(d$surv)
d$upper <- fun(d$upper)
d$lower <- fun(d$lower)
}
return(d)
}
# Adapt ylab according to the value of the argument fun
#%%%%%%%%%%%%%%%%%%%%%%%%%
.check_ylab <- function(ylab, fun){
if(!is.null(fun)){
if(ylab == "Survival probability"){
ylab <- switch(fun, log = "log(Survival probability)",
event = "Cumulative event",
cumhaz = "Cumulative hazard",
pct = "Survival probability (%)",
identity = "Survival probability",
cloglog = "log(-log(S(t)))",
"Survival probability")
}
}
ylab
}
# get survdiff pvalue
.get_pvalue <- function(fit, method, data = NULL){
data <- .get_data(fit, data)
# One group
if(length(levels(summary(fit)$strata)) == 0) return(list(val = NULL, method = NULL))
if(method == "survdiff") {
ssubset <- fit$call$subset
if(is.null(ssubset))
sdiff <- survival::survdiff(eval(fit$call$formula), data = data)
else
sdiff <- survival::survdiff(eval(fit$call$formula), data = data,
subset = eval(fit$call$subset))
pvalue <- stats::pchisq(sdiff$chisq, length(sdiff$n) - 1, lower.tail = FALSE)
return(list(val = pvalue, method = "Log-rank (survdiff)"))
} else {
tenfit <- ten(eval(fit$call$formula), data = data)
capture.output(comp(tenfit)) -> null_dev
# comp modifies tenfit object (ten class: ?survMisc::ten)
# and adds attributes with tests
attributes(tenfit)$lrt -> tests
# check str(tests) -> W:weights / pNorm:p-values
pvalue <- round(tests$pNorm[tests$W == method], 4)
test_name <- c("Log-rank (comp)", "Gehan-Breslow (generalized Wilcoxon)",
"Tarone-Ware", "Peto-Peto's modified survival estimate",
"modified Peto-Peto (by Andersen)", "Fleming-Harrington (p=1, q=1)")
# taken from ?survMisc::comp
return(list(val = pvalue, method = test_name[tests$W == method]))
}
}
# Draw risk table
# on the left
.risk_table_plot <- function(fit, data = NULL, times, legend.labs = NULL,
xlim = c(0, max(fit$time)),
risk.table.col = "black",
palette = NULL, ggtheme = ggplot2::theme_classic(),
risk.table.fontsize = 5, risk.table.title = "Number at risk by time",
risk.table.y.text = TRUE,
font.tickslab = c(12, "plain", "black"), type = "absolute"
)
{
ntimes <- length(summary(fit, times = times, extend = TRUE)$time)
if (is.null(fit$strata)) {
.strata <- factor(rep("All", length(times)))
strata_names <- "All"
strata_size <- rep(fit$n, length(.strata))
}
else {
.strata <- factor(summary(fit, times = times, extend = TRUE)$strata)
strata_names <- names(fit$strata)
nstrata = length(strata_names)
strata_size <- rep(fit$n, each = length(.strata)/nstrata)
}
risk.data <- data.frame(
strata = .clean_strata(as.factor(.strata)),
time = summary(fit, times = times, extend = TRUE)$time,
n.risk = round(summary(fit, times = times, extend = TRUE)$n.risk),
strata_size = strata_size
)
risk.data$pct.risk <- round(risk.data$n.risk*100/risk.data$strata_size)
risk.data$abs_pct.risk <- paste0(risk.data$n.risk, " (", risk.data$pct.risk, ")")
if(!is.null(fit$strata)){
variables <- .get_variables(risk.data$strata, fit, data)
for(variable in variables) risk.data[[variable]] <- .get_variable_value(variable, risk.data$strata, fit, data)
}
if (!is.null(legend.labs))
risk.data$strata <- factor(risk.data$strata, labels = legend.labs)
time <- strata <- label <- n.risk <- pct.risk <- abs_pct.risk <- NULL
# Adjust risk table labels in case of long strata
risk.table.text.y <- rev(levels(risk.data$strata))
n_strata <- length(risk.table.text.y)
# max_char <- max(nchar(risk.table.text.y))
# is_long_strata <- max_char > 5
# if(is_long_strata) risk.table.text.y <- rep("-", n_strata)
if(!risk.table.y.text) risk.table.text.y <- rep("-", n_strata)
if(type == "percentage")
dtp <- ggplot2::ggplot(risk.data,
aes(x = time, y = rev(strata), label = pct.risk, shape = rev(strata)))
else if(type == "abs_pct")
dtp <- ggplot2::ggplot(risk.data,
aes(x = time, y = rev(strata), label = abs_pct.risk, shape = rev(strata)))
else
dtp <- ggplot2::ggplot(risk.data,
ggplot2::aes(x = time, y = rev(strata), label = n.risk, shape = rev(strata)))
dtp <- dtp + scale_shape_manual(values = 1:length(levels(risk.data$strata)))+
# ggplot2::geom_point(size = 0)+
.geom_exec(ggplot2::geom_text, data = risk.data, size = risk.table.fontsize, color = risk.table.col) +
ggtheme +
ggplot2::scale_y_discrete(breaks = as.character(levels(risk.data$strata)),
labels = risk.table.text.y ) +
ggplot2::coord_cartesian(xlim = xlim) +
ggplot2::scale_x_continuous(breaks = times) +
# .ggcolor(palette)+
labs(title = risk.table.title) +
ggplot2::theme(legend.position = "none")
# if palette != hue
if(!("hue" %in% palette)){
dtp <- dtp + .ggcolor(palette, breaks = strata_names, labels = legend.labs)
}
dtp <- .set_ticks(dtp, font.tickslab = font.tickslab)
if(!risk.table.y.text)
dtp <- dtp + theme(axis.text.y = element_text(size = 50, vjust = 0.35),
axis.ticks.y = element_blank())
return(dtp)
}
# Check user defined legend labels
.check_legend_labs <- function(fit, legend.labs = NULL){
if(!is.null(legend.labs) & !inherits(fit, "survfit.cox")){
if(!is.null(fit$strata)){
if(length(fit$strata) != length(legend.labs))
stop("The length of legend.labs should be ", length(fit$strata) )
}
else{
if(length(legend.labs) != 1)
stop("The length of legend.labs should be 1")
}
}
}
# Connect survival data to the origine
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
.connect2origin <- function(d, fit, data = NULL){
base <- d[1, , drop = FALSE]
base[intersect(c('time', 'n.censor', 'std.err', "n.event"), colnames(base))] <- 0
base[c('surv', 'upper', 'lower')] <- 1.0
n.strata <- length(levels(d$strata))
# Connect each group to the origin
if (n.strata > 1) {
strata <- levels(d$strata)
base <- base[rep(1, n.strata),, drop = FALSE]
row.names(base) <- 1:nrow(base)
base$strata <- strata
base$strata <- factor(strata, levels = strata)
# update variable values
if(!inherits(fit, "survfit.cox")){
variables <- .get_variables(base$strata, fit, data)
for(variable in variables) base[[variable]] <- .get_variable_value(variable, base$strata, fit, data)
}
}
d <- rbind(base, d)
d
}
# Ge x axis major breaks
#%%%%%%%%%%%%%%%%%%%%%%%%%%%
.get_x_major_breaks <- function(p){
vv <- as.character(utils::packageVersion("ggplot2"))
cc <- utils::compareVersion(vv, "2.1.0") > 0
if(cc){
# "v>2.1.0"
breaks <- ggplot_build(p)$layout$panel_ranges[[1]]$x.major_source
}
# v<=2.1.0
else breaks <- ggplot_build(p)$panel$ranges[[1]]$x.major_source
breaks
}
# Adjust linetype manually
#%%%%%%%%%%%%%%%%%%%%%%%%%%%
.get_lty <- function(linetype){
linetype.manual = NULL
nlty <- length(linetype)
if(is.numeric(linetype)){
if(nlty > 1) {
linetype.manual <-linetype
linetype <- "strata"
}
}
else (is.character(linetype))
{
base_lty <- c("blank", "solid", "dashed", "dotted", "dotdash", "longdash", "twodash")
is_base_lty <- all(linetype %in% base_lty)
if(is_base_lty & nlty > 1){
linetype.manual <-linetype
linetype <- "strata"
}
}
list(lty = linetype, lty.manual = linetype.manual)
}
# Parse risk.table argument
#%%%%%%%%%%%%%%%%%%%%%%%
# risk.table a logical value (TRUE/FALSE) or a string ("absolute", "percentage", "abs_pct")
.parse_risk_table_arg <- function(risk.table){
res <- list(display = risk.table, type = "absolute")
if(inherits(risk.table, "character") ){
if(risk.table %in% c("absolute", "percentage", "abs_pct") )
res <- list(display = TRUE, type = risk.table)
else stop("Allowed values for risk.table are: TRUE, FALSE, 'absolute', 'percentage'")
}
res
}
# Drawing horizontal line at 50% median survival
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
.add_surv_median <-function(p, fit, type = "hv", fun = NULL, data = NULL){
x1 <- x2 <- y1 <- y2 <- NULL
draw_lines <- TRUE
med_y = 0.5
if(is.null(fun)) draw_lines <- TRUE
else if(fun %in% c("cumhaz", "cloglog")){
warning("Adding survival median lines is not allowed when fun is: ", fun)