-
Notifications
You must be signed in to change notification settings - Fork 0
/
all_visualization.R
1326 lines (1105 loc) · 48.9 KB
/
all_visualization.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
#-------------------------------
# Elements of visualization in R
#-------------------------------
library(tidyverse)
library(quantmod)
library(reshape2)
library(GGally)
library(cowplot)
library(gridExtra) # for multiple plots
library(ggridges)
library(fmsb)
library(sjPlot)
library(ggfx) # for shaded areas
data(iris)
data(diamonds)
#--------------------------------
# Scatterplot with densities in R
#--------------------------------
# 1. Create initial scatterplot
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))+
geom_point() +
labs(title = 'Scatterplot with marginal densities',
subtitle = 'Sepal.Length x Sepal.Width from Iris dataset',
y="Sepal.Width", x="Sepal.Length") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 2. Create marginal densities
xdens <- axis_canvas(p, axis = "x") +
geom_density(data = iris, aes(x = Sepal.Length, fill = Species),
alpha = 0.4, size = 0.2)
ydens <- axis_canvas(p, axis = "y", coord_flip = TRUE)+
geom_density(data = iris, aes(x = Sepal.Width, fill = Species),
alpha = 0.4, size = 0.2) + coord_flip()
p1 <- insert_xaxis_grob(p, xdens, grid::unit(.2, "null"), position = "top")
p2 <- insert_yaxis_grob(p1, ydens, grid::unit(.2, "null"), position = "right")
# 3. Create complete plot
ggdraw(p2)
#--------------------------------------------
# Scatterplot with different regression lines
#--------------------------------------------
# linear model
mod1 <- lm(Petal.Length ~ Sepal.Length, data = iris)
iris$predictions <- predict(mod1, type = 'response')
# plot
ggplot(data = iris, aes(x = Sepal.Length,y = Petal.Length, colour=Species)) +
geom_smooth(method=lm) +
geom_line(color='black', size = 1.2, aes(x=Sepal.Length, y = predictions)) +
geom_point() +
labs(title = 'Scatterplot with different regression lines',
subtitle = 'Sepal.Length x Petal.Width from Iris dataset, see if we should use mixed models',
y="Petal Length", x="Sepal Length") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#---------------------------------------------------------
# Scatterplot with regression lines and marginal densities
#---------------------------------------------------------
# Nonparametric regression model
mod1 <- lm(Sepal.Width ~ Sepal.Length, data = iris)
iris$predictions <- predict(mod1, type = 'response')
# plot
p <- ggplot(data = iris, aes(x = Sepal.Length,y = Sepal.Width, colour=Species)) +
geom_smooth(method='lm', se = FALSE) +
geom_line(color='black', size = 1.2, data = iris, aes(x=Sepal.Length, y = predictions)) +
geom_point() +
labs(title = 'Scatterplot with different regression lines and marginal densities',
subtitle = 'Sepal Width x Sepal Length from Iris dataset',
y="Petal Length", x="Sepal Width") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 2. Create marginal Boxplots
xbp <- axis_canvas(p, axis = "x") +
geom_density(data = iris, aes(x = Sepal.Length, fill = Species),
alpha = 0.4, size = 0.2)
ybp <- axis_canvas(p, axis = "y", coord_flip = TRUE)+
geom_density(data = iris, aes(x = Sepal.Width, fill = Species),
alpha = 0.4, size = 0.2) + coord_flip()
p1 <- insert_xaxis_grob(p, xbp, grid::unit(.2, "null"), position = "top")
p2 <- insert_yaxis_grob(p1, ybp, grid::unit(.2, "null"), position = "right")
# 3. Create complete plot
ggdraw(p2)
#----
# end
#----
#-----------------------------------------------------------
# Scatterplot with nonparametric lines and marginal boxplots
#-----------------------------------------------------------
# Nonparametric regression model
mod1 <- ksmooth(x = iris$Sepal.Length, y = iris$Petal.Length,
kernel = "normal", bandwidth = 1)
# plot
p <- ggplot(data = iris, aes(x = Sepal.Length,y = Petal.Length, colour=Species)) +
geom_smooth(method='loess', se = FALSE) +
geom_line(color='black', size = 1.2, data = iris, aes(x=mod1$x, y = mod1$y)) +
geom_point() +
labs(title = 'Scatterplot with different Nonparametric regression lines and marginal boxplots plots',
subtitle = 'Sepal.Length x Petal.Length from Iris dataset',
y="Petal Length", x="Sepal Length") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 2. Create marginal Boxplots
xbp <- axis_canvas(p, axis = "x") +
geom_boxplot(data = iris, aes(x = Sepal.Length, fill = Species),
alpha = 0.4, size = 0.2)
ybp <- axis_canvas(p, axis = "y", coord_flip = TRUE)+
geom_boxplot(data = iris, aes(x = Petal.Length, fill = Species),
alpha = 0.4, size = 0.2) + coord_flip()
p1 <- insert_xaxis_grob(p, xbp, grid::unit(.2, "null"), position = "top")
p2 <- insert_yaxis_grob(p1, ybp, grid::unit(.2, "null"), position = "right")
# 3. Create complete plot
ggdraw(p2)
#----
# end
#----
# subset diamonds
set.seed(2023)
indexes <- sample(diamonds$color, size = 10000, replace = FALSE)
result <- subset(diamonds, colors = indexes)
diamonds1000 <- result[sample(nrow(result), 1000), ]
diamonds1000 <- dplyr::slice_sample(result, n = 1000)
# create scatterplot
ggplot(data=diamonds1000, aes(x=carat, y=price, colour = clarity))+
geom_point(aes(size = cut)) +
viridis::scale_color_viridis(discrete=TRUE,option="magma") +
labs(title = 'Scatterplot with point sizes and colors by group',
subtitle = 'subset of diamonds dataset',
y="price", x="carat") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#---------------
# time data
#---------------
# 1. retrieve stock prices from Yahoo finance
# Tesla, Inc.
TSLA <- getSymbols("TSLA", src = "yahoo", from = "2020-01-01", to = "2020-12-31", auto.assign = FALSE)
# Apple Inc.
AAPL <- getSymbols("AAPL", src = "yahoo", from = "2020-01-01", to = "2020-12-31", auto.assign = FALSE)
# 2. Create dataset
dates <- index(TSLA)
dataset <- data.frame('dates' = dates, TSLA[, 6], AAPL[, 6])
dataset_long <- melt(dataset, id.vars = "dates")
head(dataset_long)
# 3. Time series plot of one stock
ggplot(dataset, aes(x = dates, y = TSLA.Adjusted)) +
geom_line(color = 'darkblue') +
geom_point(size = 0.6) +
labs(title = 'Time series plot',
subtitle = 'Tesla stock',
y="Adjusted closing price", x="time") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 4. Time series plot of the different stocks
ggplot(dataset_long, aes(x = dates, y = value, col = variable)) +
geom_line() +
geom_point(size = 0.6) +
labs(title = 'Multiple time series plot',
subtitle = 'Tesla and Apple stocks',
y="Adjusted closing price", x="time") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 5. Diverging ar chart of comparing to average
# compute the mean of the variable 'var3' for each 'subcategory' group
dataset_2 <- dataset %>%
mutate(Mean_TSLA = mean(TSLA.Adjusted)) %>%
mutate(Diff_TSLA = TSLA.Adjusted - Mean_TSLA) %>%
mutate(Mean_AAPL = mean(AAPL.Adjusted)) %>%
mutate(Diff_AAPL = AAPL.Adjusted - Mean_AAPL)
p1 <- ggplot(dataset_2, aes(x = dates, y = Diff_TSLA)) +
geom_bar(stat='identity', width=.5, aes(fill=Diff_TSLA),
show.legend = TRUE) +
scale_fill_continuous(name="Difference") +
labs(title = 'Diverging time series bar plot',
subtitle = 'Tesla',
y="difference", x="time") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
p2 <- ggplot(dataset_2, aes(x = dates, y = Diff_AAPL)) +
geom_bar(stat='identity', width=.5, aes(fill=Diff_AAPL),
show.legend = TRUE) +
scale_fill_continuous(name="Difference") +
labs(title = 'Diverging time series bar plot',
subtitle = 'Apple',
y="difference", x="time") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
final.plot <- grid.arrange(p1, p2, nrow = 2)
#----
# end
#----
#---------------------------------------------
# Plot time data with labels above a threshold
#---------------------------------------------
# 1. create variables
set.seed(2023)
x <- seq(from = as.Date("2011-12-30"), to = as.Date("2011-12-30") + 99, by="days")
y <- abs(rt(n = 100, df = 1, ncp = 4))
group <- rep(c('a', 'b', 'c', 'd', 'e'), 20)
ID <- 1:100
# 2. Create dataset in the form of a data frame
dataset <- data.frame(x, y, group, ID)
# 3. Create plot
ggplot(dataset, aes(x = x, y = y, color = group))+
geom_point() +
scale_colour_discrete(l = 50) + # change the color tone
geom_hline(yintercept = mean(y), linetype="dashed", color = 'black') + # add horizontal line
geom_text(aes(label = ID), dataset %>% filter(y>mean(y)),
show_guide = FALSE, vjust = -0.6, nudge_y = 1.2) + # add ID if point > criterion # fixed legend label
scale_x_date(date_labels = "%Y %b %d", date_breaks = "7 day") + # fix x-axis labels
labs(title = 'Time data with labels above average',
subtitle = 'variable y by month colored by group label, on artificial dataset',
y="value", x="day") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
axis.text.x=element_text(angle=40, hjust=1),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#----------------
# Sparklies plots
#----------------
set.seed(2023)
year = 1986:2023
variable1 = rpois(n = length(year), lambda = 4)
variable2 = rpois(n = length(year), lambda = 6)
variable3 = rpois(n = length(year), lambda = 3.6)
dataset <- data.frame('year' = year, 'v1' = variable1,
'v2' = variable2, 'v3' = variable3)
dataset <- melt(dataset, id="year")
ggplot(dataset, aes(x=year, y = value)) +
facet_grid(variable ~ ., scales = "free_y") +
geom_line(size=0.3) +
geom_point() +
scale_color_manual(values = c(NA, "red"), guide=F) +
labs(title = 'Sparklines plot with facet_grid',
subtitle = 'artificial dataset',
y="value", x="year") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#----------------------
# Circular stacked plot
#----------------------
set.seed(2023) # for reproducibility
var1 <- c(rpois(300,2), rpois(300,4), rpois(300,10))
var2 <- c(rpois(300,4), rpois(300,2), rpois(300,1))
var3 <- c(rpois(300,2), rpois(300,5), rpois(300,10))
dates <- seq(as.Date("2019-01-01"), as.Date("2021-06-18"), by="days")
length(dates)
dataset <- data.frame(var1, var2, var3, dates)
# group by months
dataset2 <- dataset %>%
mutate(month = format(dates, "%m"), year = format(dates, "%Y")) %>%
group_by(month, year) %>%
summarise(total1 = sum(var1), total2 = sum(var2), total3 = sum(var3))
tail(dataset2)
dataset22019 <- dataset2 %>% subset(year == 2019)
dataset22020 <- dataset2 %>% subset(year == 2020)
# transform data from wide to long using melt() from reshape2
data_long_2019 <- melt(dataset22019, id.vars=c("month", "year"))
data_long_2019$month <- data_long_2019[,1]
data_long_2020 <- melt(dataset22020, id.vars=c("month", "year"))
data_long_2020$month <- data_long_2020[,1]
# stacked bar plot
p1 <- ggplot(data_long_2019, aes(fill=variable, y=value, x=month)) +
geom_bar(position="stack", stat="identity") +
labs(caption = "Artificial dataset 2019") +
scale_fill_brewer() +
coord_polar() +
labs(title = 'Circular stacked bar plot 1',
subtitle = 'Variable x Month on artificial dataset',
y="Variable", x="Month",
caption = "Artificial dataset 2019") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
p2 <- ggplot(data_long_2020, aes(fill=variable, y=value, x=month)) +
geom_bar(position="stack", stat="identity") +
scale_fill_brewer() +
coord_polar() +
labs(title = 'Circular stacked bar plot 2',
subtitle = 'Variable x Month on artificial dataset',
y="Variable", x="Month",
caption = "Artificial dataset 2020") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
grid.arrange(p1, p2, nrow = 1)
#---------------------------------------------
# Plot time data with labels above a threshold
#---------------------------------------------
# 1. create variables
set.seed(2023)
x <- seq(from = as.Date("2011-12-30"), to = as.Date("2011-12-30") + 99, by="days")
y <- abs(rt(n = 100, df = 1, ncp = 4))
group <- rep(c('a', 'b', 'c', 'd', 'e'), 20)
ID <- 1:100
# 2. Create dataset in the form of a data frame
dataset <- data.frame(x, y, group, ID)
# 3. Create plot
ggplot(dataset, aes(x = x, y = y, color = group))+
geom_point() +
scale_colour_discrete(l = 50) + # change the color tone
geom_hline(yintercept = mean(y), linetype="dashed", color = 'black') + # add horizontal line
geom_text(aes(label = ID), dataset %>% filter(y>mean(y)),
show_guide = FALSE, vjust = -0.6, nudge_y = 1.2) + # add ID if point > criterion # fixed legend label
scale_x_date(date_labels = "%Y %b %d", date_breaks = "7 day") + # fix x-axis labels
labs(title = 'Time data with labels above average',
subtitle = 'variable y by month colored by group label, on artificial dataset',
y="value", x="day") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
axis.text.x=element_text(angle=40, hjust=1),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#-----------------------------------
# Histograms with overlaying density
#-----------------------------------
data(iris)
# 1. Create first plot
p1 <- ggplot(iris, aes(x = Petal.Length)) +
geom_histogram( color = 'black', fill = 'darkred', binwidth = 0.3) +
labs(title = 'Histogram of Sepal Width',
subtitle = 'iris dataset',
y="count", x="Sepal Width") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 1. Create first plot
p2 <- ggplot(iris, aes(x = Petal.Length, color = Species, fill = Species)) +
geom_histogram( color = 'black', binwidth = 0.3, alpha = 0.4) +
labs(title = 'Histogram by Species',
subtitle = 'iris dataset',
y="count", x="Sepal Width") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 2. Create thrid plot
p3 <- ggplot(iris) +
geom_histogram(aes(x = Petal.Length, y = stat(density)), fill = "black", binwidth = 0.1) +
geom_density(aes(x = Petal.Length, fill = Species, colour = Species), alpha = 0.4) +
labs(title = 'Histogram with overlying densities by Species',
subtitle = 'iris dataset',
y="density", x="Sepal Width") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 4. Create fourth plot
p4 <- ggplot(iris) +
geom_density(aes(x = Petal.Length, fill = Species), alpha = 0.4) +
labs(title = 'Densities by Species',
subtitle = 'iris dataset',
y="density", x="Sepal Width") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 3. Create final plot
final.plot <- grid.arrange(p1, p2, p3, p4, nrow = 2)
#----
# end
#----
#----------------------
# Overlaying histograms
#----------------------
# 1. Create first plot
p1 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) + # Draw overlaying histogram
geom_histogram(position = "identity", alpha = 0.3, bins = 20) +
labs(title = 'Overlaying histogram 2',
subtitle = 'iris dataset',
y="count", x="Sepal Length") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 2. Create second plot
p2 <- ggplot(iris, aes(x = Sepal.Width, fill = Species)) + # Draw overlaying histogram
geom_histogram(position = "identity", alpha = 0.3, bins = 20) +
labs(title = 'Overlaying histogram 1',
subtitle = 'iris dataset',
y="count", x="Sepal Width") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 3. Create final plot
final.plot <- grid.arrange(p1, p2, nrow = 1)
#----
# end
#----
#-----------------
# 3D barplots in R
#-----------------
library(lattice)
library(latticeExtra)
library(RColorBrewer)
# create matrix to be plotted
Matrix <- matrix(seq(1,1000, by=round(1000/20)),
nrow=5,byrow=TRUE)
rownames(Matrix)<-LETTERS[1:5]
colnames(Matrix)<-letters[1:4]
# color
redcol = colorRampPalette(brewer.pal(9,'Reds'))(150)
# 3D barplot
cloud(Matrix, panel.3d.cloud = panel.3dbars, zoom = 0.96,
xbase = 0.4, ybase = 0.4, zlim = c(0, max(Matrix)),
scales = list(arrows = FALSE, just = "right"),
xlab = NULL, ylab = NULL, zlab = NULL,
par.settings = list(axis.line = list(col = "transparent")),
col.facet = level.colors(Matrix,
at = do.breaks(range(Matrix), 30),
col.regions = redcol,
colors = TRUE),
main='3D Barplot',
colorkey = list(col = redcol, at = do.breaks(range(Matrix), 30)),
screen = list(z = 20, x = -60))
#----
# end
#----
#-------------------------------------------------
# Ridgeplots:
# Different distribution density on the same graph
# on different levels
#-------------------------------------------------
# plot
ggplot(iris, aes(x = Sepal.Length, y = Species, fill = Species)) +
geom_density_ridges(alpha = 0.4) + # create ridges
labs(title = 'Multiple densities on different levels',
subtitle = 'Ridge plot with ggridges on iris dataset',
y="Species", x="density Sepal Length") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#------------------
# Stacked bar plots
#------------------
data(diamonds)
diamonds2 <- diamonds %>%
group_by(cut) %>%
count(color) %>%
mutate(percentage = n/nrow(diamonds) * 100) %>%
rename(nobservations = n)
p1 <- ggplot(diamonds2, aes(x = cut, y = percentage, fill = color)) +
geom_bar(stat = 'identity') +
coord_flip() +
labs(title = 'Stacked bar plot with percentages',
subtitle = 'Diamonds dataset',
y="percentage of color", x="cut") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
p2 <- ggplot(diamonds2, aes(x = cut, y = nobservations, fill = color)) +
geom_bar(stat = 'identity') +
coord_flip() +
labs(title = 'Stacked bar plot with counts',
subtitle = 'Diamonds dataset',
y="count of color", x="cut") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
grid.arrange(p1, p2, nrow = 2)
#----
# end
#----
#----------------------------------------------------
# Box plots and violin plots with mean color gradient
#----------------------------------------------------
iris2 <- iris %>%
group_by(Species) %>%
mutate(Mean_SL = mean(Sepal.Length))
# multiple box plots
p1 <- ggplot(iris2, aes(x = Species, y = Sepal.Length)) +
geom_boxplot(aes(fill=Mean_SL)) +
geom_point(aes(x = Species, y = Sepal.Length), position = 'jitter', size = 0.4) +
scale_fill_gradient2('mean(Sepal Length)', low = "blue4",
mid = "white", high = "firebrick4",
midpoint = mean(iris2$Sepal.Length)) +
facet_wrap(~Species, scales="free") +
labs(title = 'Box plots for Sepal Length x Species, for each Species group',
subtitle = "Color gradient indicate the mean of the variable 'Sepal Length'",
caption = "irir dataset") +
theme(axis.text=element_text(size=5),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=6, face="italic", color="darkred"))
# multiple violin plots
p2 <-ggplot(iris2, aes(x = Species, y = Sepal.Length)) +
geom_violin(aes(fill=Mean_SL)) +
geom_point(aes(x = Species, y = Sepal.Length), position = 'jitter', size = 0.4) +
scale_fill_gradient2('mean(Sepal Length)', low = "blue4",
mid = "white", high = "firebrick4",
midpoint = mean(iris2$Sepal.Length)) +
facet_wrap(~Species, scales="free") +
labs(title = 'Violin plots for Sepal Length x Species, for each Species group',
subtitle = "Color gradient indicate the mean of the variable 'Sepal Length'",
caption = "irir dataset") +
theme(axis.text=element_text(size=5),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=6, face="italic", color="darkred"))
final.plot <- grid.arrange(p1, p2, nrow = 2)
#----
# end
#----
#-------------------------
# Summary of distributions
#-------------------------
# 1 . Summary of distributions
ggpairs(iris, ggplot2::aes(colour = Species, alpha = 0.4)) +
labs(title = 'Summary of distributions with ggpairs',
subtitle = 'all variables x all variables, by group, iris dataset',
y="", x="") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=9, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#------------------------
# Visualization dashboard
#------------------------
data(diamonds)
# 1. scatterplot
diamond.plot <- ggplot(data=diamonds, aes(x=carat, y=price, colour = clarity))+
geom_point(aes(size = cut))+
labs(title = 'Example of Scatterplot',
subtitle = 'diamonds dataset',
y="price", x="carat") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 2. boxplot
diamond.bxplot <- ggplot(diamonds, aes(x = cut, y=price)) +
geom_boxplot(aes(fill = color))+
labs(title = 'Example of Boxplots',
subtitle = 'diamonds dataset',
y="price", x="cut") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 3. violin plot
diamond.violinplot <- ggplot(diamonds, aes(x = cut, y=price)) +
geom_violin(aes(fill = color)) +
labs(title = 'Example of Violin plots',
subtitle = 'diamonds dataset',
y="price", x="cut") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# 4. bar plot
diamond.barpot <- ggplot(diamonds, aes(x = clarity, fill=cut)) +
geom_bar() +
coord_flip() +
labs(title = 'Example of Bar plots',
subtitle = 'diamonds dataset',
y="count", x="cut") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
grid.arrange(diamond.plot, diamond.bxplot, diamond.violinplot, diamond.barpot,
nrow = 2)
#----
# end
#----
#---------------------------
# Parallel coordinates plots
#---------------------------
ggparcoord(iris, columns = 1:4, groupColumn = 5, order = "anyClass",
showPoints = TRUE, alphaLines = 0.4) +
labs(title = 'Parallel coordinates plots',
subtitle = 'iris dataset',
y="value", x="Species") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#--------------
# Pareto charts
#--------------
# taken from:https://rpubs.com/dav1d00/ggpareto
# creating a factor variable:
dataset <- rep(c(LETTERS[1:5]), c(30, 66, 6, 42, 21))
# implementing the function:
ggpareto <- function(x) {
title <- deparse(substitute(x))
x <- data.frame(modality = na.omit(x))
Df <- x %>% group_by(modality) %>% summarise(frequency=n()) %>%
arrange(desc(frequency))
Df$modality <- ordered(Df$modality, levels = unlist(Df$modality, use.names = F))
Df <- Df %>% mutate(modality_int = as.integer(modality),
cumfreq = cumsum(frequency), cumperc = cumfreq/nrow(x) * 100)
nr <- nrow(Df)
N <- sum(Df$frequency)
Df_ticks <- data.frame(xtick0 = rep(nr +.55, 11), xtick1 = rep(nr +.59, 11),
ytick = seq(0, N, N/10))
y2 <- c(" 0%", " 10%", " 20%", " 30%", " 40%", " 50%", " 60%", " 70%", " 80%", " 90%", "100%")
library(ggplot2)
g <- ggplot(Df, aes(x=modality, y=frequency)) +
geom_bar(stat="identity", aes(fill = modality_int)) +
geom_line(aes(x=modality_int, y = cumfreq, color = modality_int)) +
geom_point(aes(x=modality_int, y = cumfreq, color = modality_int), pch = 19) +
scale_y_continuous(breaks=seq(0, N, N/10), limits=c(-.02 * N, N * 1.02)) +
scale_x_discrete(breaks = Df$modality) +
guides(fill = FALSE, color = FALSE) +
annotate("rect", xmin = nr + .55, xmax = nr + 1,
ymin = -.02 * N, ymax = N * 1.02, fill = "white") +
annotate("text", x = nr + .8, y = seq(0, N, N/10), label = y2, size = 3.5) +
geom_segment(x = nr + .55, xend = nr + .55, y = -.02 * N, yend = N * 1.02, color = "grey50") +
geom_segment(data = Df_ticks, aes(x = xtick0, y = ytick, xend = xtick1, yend = ytick)) +
labs(title = 'Pareto plot (frequency and percentage by group)',
subtitle = 'artificial dataset',
y="Frequency", x="Group") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
return(list(graph = g, Df = Df[, c(3, 1, 2, 4, 5)]))
}
# applying the function to the factor variable:
ggpareto(dataset)
#----
# end
#----
#-------------
# Mosaic plots
#-------------
# using diamonds dataset for illustration
df <- diamonds %>%
group_by(cut, clarity) %>%
summarise(count = n()) %>%
mutate(cut.count = sum(count),
prop = count/sum(count)) %>%
ungroup()
ggplot(df, aes(x = cut, y = prop, width = cut.count, fill = clarity)) +
geom_bar(stat = "identity", position = "fill", colour = "black") +
facet_grid(~cut, scales = "free_x", space = "free_x") +
scale_fill_brewer(palette = "RdYlBu") +
labs(title = 'Mosaic plot of frequency for two nomial or categorical variables',
subtitle = 'Diamonds dataset',
y="features", x="correlation") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#----------------------
# Plotting correlations
#----------------------
# 1. Download dataset
dataset <- read.csv('C:/Users/julia/OneDrive/Desktop/github/11. Customer_churn_analysis/Telco-Customer-Churn.csv', na.strings = c('','?'))
dataset$ChurnDummy <- as.factor(ifelse(dataset$Churn == 'Yes', 1, 0))
dataset = na.omit(dataset) # removing missing values
# recapitulation of training set with separation between predictors and outcomes
rec_obj <- dataset %>%
recipe(Churn ~ .) %>%
step_rm(customerID) %>%
step_naomit(all_outcomes(), all_predictors()) %>%
step_discretize(tenure, options = list(cuts = 6)) %>%
step_log(TotalCharges) %>%
step_mutate(Churn = ifelse(Churn == "Yes", 1, 0)) %>%
step_dummy(all_nominal(), -all_outcomes()) %>%
step_center(all_predictors(), -all_outcomes()) %>%
step_scale(all_predictors(), -all_outcomes()) %>%
prep()
summary(rec_obj)
print(summary(rec_obj), n = 36)
# design matrix of predictors and vector of outcomes as numeric
features_train_tbl <- juice(rec_obj, all_predictors(), composition = "matrix")
response_train_vec <- juice(rec_obj, all_outcomes()) %>% pull()
# analysis of correlations
corrr_analysis <- features_train_tbl %>%
as_tibble() %>%
mutate(Churn = response_train_vec) %>%
correlate() %>%
focus(Churn)
# positive and negative correlated predictors
pos <- corrr_analysis %>%
filter(Churn > 0)
neg <- corrr_analysis %>%
filter(Churn < 0)
# plot
ggplot(corrr_analysis, aes(x = Churn, y = fct_reorder(term, desc(Churn)))) +
geom_point() +
geom_segment(aes(xend = 0, yend = term), data = under, color = 'darkred') +
geom_point(data = neg, color = 'darkred') +
geom_segment(aes(xend = 0, yend = term), data = over, color = "darkblue") +
geom_point(data = pos, color = "darkblue") +
labs(title = 'Plotting correlations of features to a response (even nominal)',
subtitle = 'Telco dataset',
y="features", x="correlation") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
# corelogram
library(corrplot)
par(mfrow = c(1,2))
corrplot(cor(iris[,1:4]), method="pie",
main = '')
corrplot(cor(iris[,1:4]), method="number",
main = '')
#----
# end
#----
#-----------------------------------------------------
# Plotting odds ratios from binary logistic regression
#-----------------------------------------------------
# 1. Download dataset
dataset <- read.csv('C:/Users/julia/OneDrive/Desktop/github/11. Customer_churn_analysis/Telco-Customer-Churn.csv', na.strings = c('','?'))
dataset$ChurnDummy <- as.factor(ifelse(dataset$Churn == 'Yes', 1, 0))
dataset = na.omit(dataset) # removing missing values
model.1.lr <- glm(formula = ChurnDummy ~ gender + SeniorCitizen + Partner + Dependents +
tenure + PhoneService + MultipleLines +
InternetService +OnlineSecurity + OnlineBackup +
DeviceProtection + TechSupport + StreamingTV +
StreamingMovies + Contract + PaperlessBilling +
PaymentMethod + MonthlyCharges + TotalCharges,
data = dataset, family = "binomial")
summary <- summary(model.1.lr)
# export the results in LaTex document
print(xtable(summary$coefficients, type = "latex"), file = "Customer_churn_analysis_tables.tex")
# Confidence intervals
exp(confint(model.1.lr))
# plot coefficients odds ratio
plot_model(model.1.lr, vline.color = "red",
sort.est = TRUE, show.values = TRUE) +
labs(title = 'Plotting odds ratios - Binary Logistic regression',
subtitle = 'Telco dataset',
y="features", x="Odds ratio") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8),
plot.subtitle=element_text(size=10, face="italic", color="darkred"),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"))
#----
# end
#----
#----------------------
# Ploting likert scales
#----------------------
library(likert)
data("pisaitems")
# capture Likert data by group
data <- likert(pisaitems[,2:6], grouping=pisaitems$CNT)
# plot
plot(data) +