-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproject7.Rmd
811 lines (665 loc) · 27.7 KB
/
project7.Rmd
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
---
title: "Chapter 4: Publication ready plots using ggpubr"
description: |
Learn how to make publication ready plots using the ggpubr package.
author:
- name: Jewel Johnson
date: 01-06-2022
base_url: https://jeweljohnsonj.github.io/jeweljohnson.github.io/
output:
distill::distill_article:
toc_depth: 3
preview: photos/ggpubr.png
---
```{r setup, include=FALSE}
library(ggpubr)
library(rmarkdown)
library(viridis)
library(knitr)
library(dplyr)
library(tidyr)
library(tibble)
library(palmerpenguins)
library(PairedData)
knitr::opts_chunk$set(echo = TRUE)
```
```{r, xaringanExtra-clipboard, echo=FALSE}
htmltools::tagList(
xaringanExtra::use_clipboard(
button_text = "<i class=\"fa fa-clone fa-2x\" style=\"color: #301e64\"></i>",
success_text = "<i class=\"fa fa-check fa-2x\" style=\"color: #90BE6D\"></i>",
error_text = "<i class=\"fa fa-times fa-2x\" style=\"color: #F94144\"></i>"
),
rmarkdown::html_dependency_font_awesome()
)
```
---
# xaringanExtra package will help us to have inbuilt tabs insdie the article
---
```{r panelset, echo=FALSE}
xaringanExtra::use_panelset()
```
---
# loading javascipt file which helps in folding outputs similar to code folding
---
<script src="js/output_folding.js"></script>
---
#start editing from here
---
## Introduction to ggpubr package
If you are a researcher who wants to have publication-ready plots but does not want to get hassled by the `ggplot2` package, then let me introduce you to the`ggpubr` package. Using this package you can make publication grade plots without spending too much time modifying things. Even if you are a beginner in R programming and does not know how to use the`ggplot2` package, you will still be able to plot graphs using the `ggpubr` package because of how easy the syntax is. But having prior knowledge of the `ggplot2` package will surely make things easier, and an experienced person will know that any plot which can be plotted using `ggpubr` can also be plotted using `ggplot2`. So let us start.
First things first, install the `ggpubr` package and load it in the library.
```{r, eval=FALSE}
install.packages("ggpubr")
library(ggpubr)
```
We will first see what all plots can be plotted.
## Plots in ggpubr package
### 1. Balloon plot
The balloon plot is similar to bar plots as it is used to represent a large categorical dataset. The size and colour of the dot can be attributed to different values in the dataset.
```{r, layout="l-body-outset"}
# library(viridis) for colour palette
ggballoonplot(mtcars, fill = "value") +
scale_fill_viridis(option = "turbo")
```
### 2. Bar plot
A simple bar graph which is used for representing categorical data. By using the `add` function inside the main plot function, you can easily display summary statistics like mean, median etc. and various types of errors like standard error, standard deviation and various others. You can view the whole list of features [here](https://rpkgs.datanovia.com/ggpubr/reference/ggbarplot.html).
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
ggbarplot(penguins,
x = "species",
y = "bill_length_mm",
add = c("mean_sd"),
fill = "species",
label = TRUE,
lab.nb.digits = 2,
lab.vjust = -2.2,
lab.col = "red",
title = "Mean bill length of penguins",
subtitle = "Error bars shows standard deviation",
xlab = "Species of penguins",
ylab = "Bill length (mm)",
ylim = c(0,60),
palette = "npg")
```
### 3. Box plot
Standard box plot graph. Like in the previous graph you can specify colour palettes from the scientific journal palettes featured in the `ggsci` R package.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
ggboxplot(penguins ,
x = "species",
y = "bill_depth_mm",
title = "Mean bill depth of penguins",
xlab = "Species of penguins",
ylab = "Bill depth (mm)",
color = "species",
palette = "futurama",
add = "jitter",
shape = "species")
```
### 4. Violin plot
A simple violin plot.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
ggviolin(penguins ,
x = "species",
y = "bill_depth_mm",
title = "Mean bill depth of penguins",
xlab = "Species of penguins",
ylab = "Bill depth (mm)",
fill = "species",
palette = "npg",
add = "boxplot",
shape = "species")
```
### 5. Density plot
Standard density plot.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
ggdensity(penguins,
x = "body_mass_g",
color = "species",
rug = TRUE,
fill = "species",
add = "mean",
title = "Mean body mass of penguins",
xlab = "Body mass (g)",
palette = "lancet")
```
### 6. Donut chart
Similar to a pie diagram. Also please note that you don't have to explicitly mention x and y parameters in the command. You can simply just type the column names, the first column name will be shown on the x-axis and the second on the y axis.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
# library(dplyr)
# library(tidyr)
penguins_freq <- penguins %>% drop_na() %>%
group_by(species) %>%
summarise(frequency = length(species))
labs <- paste0(penguins_freq$species, " (", round((penguins_freq$frequency/sum(penguins_freq$frequency))*100, digits = 0), "%)")
ggdonutchart(penguins_freq,
"frequency",
label = labs,
fill = "species",
palette = "ucscgb",
lab.pos = "in",
title = "Frequency of penguins")
```
### 7. Pie chart
Simple pie chart.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
# library(dplyr)
# library(tidyr)
penguins_freq <- penguins %>% drop_na() %>%
group_by(species) %>%
summarise(frequency = length(species))
labs <- paste0(penguins_freq$species, " (", round((penguins_freq$frequency/sum(penguins_freq$frequency))*100, digits = 0), "%)")
ggpie(penguins_freq,
"frequency",
label = labs,
fill = "species",
palette = "futurama",
lab.pos = "in",
title = "Frequency of penguins")
```
### 8. Dot chart
This is an upgrade from bar charts where the data is displayed with minimum clutter in the form of dots. This allows the readers to not get bothered about things like the slope of a line in case of line plots, or width of bars in case of bar charts or any other confusing aesthetics of a plot. You can read more about this graph [here](https://doi.org/10.2307/2288400). It is also called "Cleveland dot plots" named after the founder of this plot.
```{r, fig.align='center', fig.height= 7, fig.width= 6}
mtcars %>% rownames_to_column(var = "car_names") %>%
mutate(cyl = as.factor(cyl)) %>%
ggdotchart("car_names",
"mpg",
color = "cyl",
palette = "aaas",
sorting = "ascending",
rotate = TRUE,
y.text.col = TRUE,
dot.size = 2,
ylab = "Miles per gallon of fuel",
title = "Mileage of different cars",
ggtheme = theme_pubr()) + theme_cleveland()
```
### 9. Dot plot
Simple dot plot. Similar to a box plot. You can also overlay a box plot or a violin plot over the dot plot using the `add` function inside the main function.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
ggdotplot(penguins ,
x = "species",
y = "bill_depth_mm",
title = "Mean bill depth of penguins",
subtitle = "Error bars shows standard deviation",
xlab = "Species of penguins",
ylab = "Bill depth (mm)",
fill = "species",
add = "mean_sd",
palette = "locuszoom")
```
### 10. Histogram plot
The same function as that of a density plot but the data is represented in bars.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
gghistogram(penguins,
x = "body_mass_g",
add = "mean",
fill = "species",
rug = TRUE,
title = "Body mass of penguins",
xlab = "Body mass (g)",
ylab = "Frequency",
palette = "startrek")
```
### 11. Line plot
A simple line plot.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
ggline(penguins,
x = "body_mass_g",
y = "bill_depth_mm",
linetype = "species",
shape = "species",
color = "species",
title = "Body mass vs Bill depth",
xlab = "Body mass (g)",
ylab = "Bill depth (mm)",
palette = "startrek")
```
### 12. Plotting paired data
This is essentially a box plot but for paired data. Widely used to represent treatment groups showing before and after results of the same sample. We will be using the Anorexia dataset from the `PairedData` package in R. It features weights of girls before and after treatment for Anorexia.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("PairedData")
# library(PairedData)
data("Anorexia")
Anorexia %>%
ggpaired(cond1 = "Prior",
cond2 = "Post",
title = "Weights of girls before and after treatment for anorexia",
xlab = "Condition",
ylab = "Weight (lbs)",
fill = "condition",
line.color = "darkgreen",
line.size = 0.2,
palette = "simpsons")
```
### 13. Quantile-Quantile plot
Quantile-Quantile plot or QQ plot is useful in assessing the distribution of a data. A data having normal distribution will be shown as a straight line of the formula 'y=x' in the QQ plot. Points outside the confidence interval are outliers in the data.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
penguins %>% ggqqplot("body_mass_g",
color = "species",
palette = "aaas",
title = "Quantile-Quantile plot")
```
### 14. Scatter plot
A simple scatter plot.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
penguins %>% filter(species == "Chinstrap") %>%
ggscatter("body_mass_g",
"bill_length_mm",
add = "reg.line",
add.params = list(color = "darkred", fill = "yellow"),
cor.coef = TRUE,
cor.method = "pearson",
conf.int = TRUE,
title = "Body mass distribution of Chinstrap penguins",
subtitle = "Correlation method used was Pearson",
xlab = "Body mass (g)",
ylab = "Bill lenght (mm)")
```
You can also use scatter plot for data having different categories. Using `ellipse=TRUE` you can group data to its category.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
penguins %>%
ggscatter("body_mass_g",
"bill_length_mm",
color = "species",
alpha = 0.5,
palette = "d3",
ellipse = TRUE, #adds an ellipse to group data of different category
title = "Body mass vs Bill length",
xlab = "Body mass (g)",
ylab = "Bill length (mm)")
```
You can also label points in the scatter plot using the `label` function.
```{r, fig.align='center',layout="l-body-outset", fig.width= 8}
mtcars %>% rownames_to_column(var = "car_names") %>%
mutate(cyl = as.factor(cyl)) %>%
ggscatter("wt",
"mpg",
color = "cyl",
palette = "nejm",
xlab = "Weight (1000 lbs)",
ylab = "Miles per gallon of fuel",
title = "Mileage vs Weight of different cars",
label = "car_names",
repel = TRUE,
ggtheme = theme_pubr()) + theme_cleveland()
```
### 15. Scatter Plot with Marginal Histograms
This is plot is a combination of scatter plot and histograms.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
penguins %>%
ggscatterhist("body_mass_g",
"bill_length_mm",
color = "species",
alpha = 0.5, size = 2,
palette = "futurama",
margin.params = list(fill = "species", color = "black", size = 0.2),
title = "Body mass distribution of penguins",
xlab = "Body mass (g)",
ylab = "Bill length (mm)")
```
You can also choose to show box plots.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
penguins %>%
ggscatterhist("body_mass_g",
"bill_depth_mm",
color = "species",
alpha = 0.5, size = 2,
palette = "futurama",
margin.plot = "boxplot",
title = "Body mass vs Bill depth",
xlab = "Body mass (g)",
ylab = "Bill depth (mm)",
ggtheme = theme_bw())
```
## Other functions in ggpubr package
### 1. Statistical tests
You can do various statistical tests using the functions in the `ggpubr` package. We will be using the Anorexia dataset in the `PairedData` package in R. In the code given below, we are doing a Wilcoxon test to compare the mean weights of girls before treatment to the mean weights of girls post-treatment. Since the data is paired we will indicate it by the `paired = TRUE` function. A word of caution! Before starting to do statistical tests please ensure whether you can fulfil conditions for using parametric tests or not using or data. You can check whether your data is normally distributed using a QQ plot or by using any normality tests.
```{r, eval=FALSE}
# install.packages("PairedData")
# library(PairedData)
# library(dplyr)
# library(tidyr)
data("Anorexia")
# tidying the data
Anorexia_new <- Anorexia %>%
pivot_longer(c(Prior, Post), names_to = "condition", values_to = "weight")
compare_means(weight ~ condition, Anorexia_new, paired = TRUE)
```
```{r, echo=FALSE}
data("Anorexia")
Anorexia_new <- Anorexia %>%
pivot_longer(c(Prior, Post), names_to = "condition", values_to = "weight")
paged_table(compare_means(weight ~ condition, Anorexia_new, paired = TRUE))
```
You can also do parametric tests like ANOVA and its non-parametric version; the Kruskal-Wallis test, which can be followed by multiple pairwise comparisons.
```{r, eval=FALSE}
compare_means(body_mass_g ~ species, penguins, method = "anova")
compare_means(body_mass_g ~ species, penguins, method = "kruskal.test")
```
```{r, echo=FALSE}
paged_table(compare_means(body_mass_g ~ species, penguins, method = "anova"))
paged_table(compare_means(body_mass_g ~ species, penguins, method = "kruskal.test"))
```
```{r, eval=FALSE}
# multiple pairwise comparisons
# when there is more than two levels, the function automatically does pairwise comparisons
compare_means(body_mass_g ~ species, penguins)
```
```{r, echo=FALSE}
# multiple pairwise comparisons
# when there is more than two levels, the function automatically does pairwise comparisons
paged_table(compare_means(body_mass_g ~ species, penguins))
```
### 2. Descriptive statistics by groups
Using the function `desc_statby()` we can get the summary statistics of a dataset in the form of a data frame. Similar to the `summary()` function in base R.
```{r, eval=FALSE}
desc_statby(penguins, measure.var = "body_mass_g", grps = "species")
```
```{r, echo=FALSE}
paged_table(desc_statby(penguins, measure.var = "body_mass_g", grps = "species"))
```
You can also show the data as a table using the `ggtexttable()` function.
```{r}
summary <- desc_statby(penguins, measure.var = "body_mass_g", grps = "species")
summary_short <- summary %>% dplyr::select(species, mean, median, se, sd)
summary_tbl <- ggtexttable(summary_short, rows = NULL, theme = ttheme("mRed")) # use ?ttheme to see more themes
summary_tbl
```
### 3. Showing p-values and statistical results within plots
Using various functions you can show statistical outputs within the plots.
Using Wilcoxon test for paired data.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("PairedData")
# library(PairedData)
data("Anorexia")
Anorexia %>%
ggpaired(cond1 = "Prior",
cond2 = "Post",
title = "Weights of girls before and after treatment for anorexia",
xlab = "Condition",
ylab = "Weight (lbs)",
fill = "condition",
line.color = "darkgreen",
line.size = 0.2,
palette = "simpsons") + stat_compare_means(paired = TRUE)
```
Using t-test
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
penguins %>% filter(species == "Adelie" & island == c("Biscoe","Torgersen")) %>%
ggboxplot(x = "island",
y = "bill_depth_mm",
title = "Mean bill depth of penguins",
xlab = "Island",
ylab = "Bill depth (mm)",
color = "island",
palette = "futurama",
add = "jitter",
shape = "island") + stat_compare_means(method = "t.test")
```
Using ANOVA test and t-test as post hoc test. For pairwise comparison, we have to manually list out the pairwise comparisons that we want.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
# listing out pairwise comparisons
compare <- list(c("Adelie", "Chinstrap"), c("Adelie", "Gentoo"), c("Chinstrap", "Gentoo"))
ggboxplot(penguins ,
x = "species",
y = "bill_depth_mm",
title = "Mean bill depth of penguins",
xlab = "Species of penguins",
ylab = "Bill depth (mm)",
color = "species",
palette = "futurama",
add = "jitter",
shape = "species") +
stat_compare_means(method = "anova", label.y = 25) + #anova test
stat_compare_means(comparisons = compare, method = "t.test") # post hoc test using t-test
```
Using Kruskal-Wallis test and Wilcoxon test as post hoc test.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
compare <- list(c("Adelie", "Chinstrap"), c("Adelie", "Gentoo"), c("Chinstrap", "Gentoo"))
ggboxplot(penguins ,
x = "species",
y = "bill_depth_mm",
title = "Mean bill depth of penguins",
xlab = "Species of penguins",
ylab = "Bill depth (mm)",
color = "species",
palette = "futurama",
add = "jitter",
shape = "species") +
stat_compare_means(label.y = 25) + #anova test
stat_compare_means(comparisons = compare) # post hoc test using t-test
```
You can also choose to show only asterisks as significance levels
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
compare <- list(c("Adelie", "Chinstrap"), c("Adelie", "Gentoo"), c("Chinstrap", "Gentoo"))
ggboxplot(penguins ,
x = "species",
y = "bill_depth_mm",
title = "Mean bill depth of penguins",
xlab = "Species of penguins",
ylab = "Bill depth (mm)",
color = "species",
palette = "futurama",
add = "jitter",
shape = "species") +
stat_compare_means(label.y = 25) +
stat_compare_means(comparisons = compare, label = "p.signif")
```
For illustrative purposes, I have used box plots for showing p-values and statistical test results, but you can do the same with most of the other types of graphs shown in this chapter.
### 4. Faceting plots into grids
You can also facet different plots into grids using the function `facet.by`.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("palmerpenguins")
# library(palmerpenguins)
penguins %>% drop_na() %>%
ggscatter("body_mass_g",
"bill_length_mm",
color = "species",
alpha = 0.5,
palette = "d3",
facet.by = c("island", "sex"), # faceting graphs via island and sex categories
title = "Body mass vs Bill length",
xlab = "Body mass (g)",
ylab = "Bill length (mm)")
```
### 5. Adding paragraph
You can also add a paragraph beneath the plot of your interest using the `ggparagraph()` and `ggarrange()` functions.
```{r,fig.align='center',layout="l-body-outset"}
# install.packages("PairedData")
# library(PairedData)
data("Anorexia")
text <- paste("The above dataset shows the weight (in lbs) of 17 girls before",
"and after they got treatment for anorexia.", sep = " ")
text_plot <- ggparagraph(text, face = "bold", size = 12)
plot <- Anorexia %>%
ggpaired(cond1 = "Prior",
cond2 = "Post",
title = "Weights of girls before and after treatment for anorexia",
xlab = "Condition",
ylab = "Weight (lbs)",
fill = "condition",
line.color = "darkgreen",
line.size = 0.2,
palette = "simpsons")
ggarrange(plot, text_plot,
ncol = 1, nrow = 2,
heights = c(1, 0.3))
```
### 6. Having plots adjacent to each other
You can use the `ggarrange()` function to place different plots together.
```{r,fig.align='center', fig.height= 8, fig.width= 11}
# install.packages("palmerpenguins")
# library(palmerpenguins)
bar_plot <- ggbarplot(penguins,
x = "species",
y = "bill_length_mm",
add = c("mean_sd"),
fill = "species",
label = TRUE,
lab.nb.digits = 2,
lab.vjust = -2.2,
lab.col = "red",
title = "Mean bill length of penguins",
subtitle = "Error bars shows standard deviation",
xlab = "Species of penguins",
ylab = "Bill length (mm)",
ylim = c(0,60),
palette = "npg")
histogram <- gghistogram(penguins,
x = "body_mass_g",
add = "mean",
fill = "species",
rug = TRUE,
title = "Body mass of penguins",
xlab = "Body mass (g)",
ylab = "Frequency",
palette = "startrek")
summary <- desc_statby(penguins, measure.var = "body_mass_g", grps = "species")
summary_short <- summary %>% dplyr::select(species, mean, median, se, sd)
summary_tbl <- ggtexttable(summary_short, rows = NULL, theme = ttheme("mRed")) # use ?ttheme to see more themes
# arranging plots together
ggarrange(bar_plot, histogram,
ncol = 2, nrow = 2, labels = c("A", "B"),
heights = c(1, 0.3))
```
If you are arranging three graphs it is better to use the `grid.arrange()` function from the `gridExtra` package in R.
```{r,fig.align='center', fig.height= 8, fig.width= 11}
# install.packages("palmerpenguins")
# library(palmerpenguins)
bar_plot <- ggbarplot(penguins,
x = "species",
y = "bill_length_mm",
add = c("mean_sd"),
fill = "species",
label = TRUE,
lab.nb.digits = 2,
lab.vjust = -2.2,
lab.col = "red",
title = "Mean bill length of penguins",
subtitle = "Error bars shows standard deviation",
xlab = "Species of penguins",
ylab = "Bill length (mm)",
ylim = c(0,60),
palette = "npg")
histogram <- gghistogram(penguins,
x = "body_mass_g",
add = "mean",
fill = "species",
rug = TRUE,
title = "Body mass of penguins",
xlab = "Body mass (g)",
ylab = "Frequency",
palette = "startrek")
summary <- desc_statby(penguins, measure.var = "body_mass_g", grps = "species")
summary_short <- summary %>% dplyr::select(species, mean, median, se, sd)
summary_tbl <- ggtexttable(summary_short, rows = NULL, theme = ttheme("mRed")) # use ?ttheme to see more themes
# arranging three plots together
layout_matrix <- matrix(c(1, 1, 2, 2, 4, 3, 3, 4), nrow = 2, byrow = TRUE)
library(gridExtra)
grid.arrange(bar_plot, histogram, summary_tbl, layout_matrix = layout_matrix)
```
## Saving your plot
Using the function `ggexport()` you can save your plot. Tweak width and height accordingly and also change the resolution to fit your needs.
```{r,eval=FALSE}
# install.packages("palmerpenguins")
# library(palmerpenguins)
penguins %>%
ggscatterhist("body_mass_g",
"bill_length_mm",
color = "species",
alpha = 0.5, size = 2,
palette = "futurama",
margin.params = list(fill = "species", color = "black", size = 0.2),
title = "Body mass distribution of penguins",
xlab = "Body mass (g)",
ylab = "Bill length (mm)") %>%
ggexport(filename = "my_plot.png", width = 800, height = 600, res = 150)
```
## Summary
In this chapter we learned how to plot publication standard graphs using the `ggpubr` package in R. Even with little to no experience in using the `ggplot2` package in R, one can plot graphs with ease using the `ggpubr` package. To quickly recap, from this chapter we saw;
1. How to plot around 15 different types of graphs
2. How to facet plots
3. How to do basic statistical tests and visualize them within graphs
4. How to add paragraph text under the graphs
5. How to group different graphs into one single file
I hope this chapter was useful to you. See you next time!
---
# buttons for navigation
---
<br>
<a href="project3.html" class="btn button_round" style="float: left;">Previous chapter:<br> 3: Even more customizations in ggplot2</a>
## References
1. Alboukadel Kassambara (2020). ggpubr: 'ggplot2' Based Publication Ready Plots. R package version 0.4.0.
https://CRAN.R-project.org/package=ggpubr
2. Horst AM, Hill AP, Gorman KB (2020). palmerpenguins: Palmer Archipelago (Antarctica) penguin data. R package version 0.1.0.
https://allisonhorst.github.io/palmerpenguins/
3. Stephane Champely (2018). PairedData: Paired Data Analysis. R package version 1.1.1.
https://CRAN.R-project.org/package=PairedData
4. William S. Cleveland & Robert McGill (1984) Graphical Perception: Theory, Experimentation, and Application to the Development of Graphical Methods, Journal of the American Statistical Association, 79:387, 531-554, DOI: 10.1080/01621459.1984.10478080
5. Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2021). dplyr: A Grammar of Data Manipulation. R package
version 1.0.7. https://CRAN.R-project.org/package=dplyr
6. Hadley Wickham (2021). tidyr: Tidy Messy Data. R package version 1.1.4. https://CRAN.R-project.org/package=tidyr
7. H. Wickham. ggplot2: Elegant Graphics for Data Analysis. Springer-Verlag New York, 2016.
8. Simon Garnier, Noam Ross, Robert Rudis, Antônio P. Camargo, Marco Sciaini, and Cédric Scherer (2021). Rvision -
Colorblind-Friendly Color Maps for R. R package version 0.6.2.
## Last updated on {.appendix}
```{r, echo=FALSE}
Sys.time()
```
---
# social media share buttons
---
<!-- adding share buttons on the right side of the page -->
<!-- AddToAny BEGIN -->
<div class="a2a_kit a2a_kit_size_32 a2a_floating_style a2a_vertical_style" style="right:0px; top:150px; data-a2a-url="https://jeweljohnsonj.github.io/jeweljohnson.github.io/" data-a2a-title="One-carat Blog">
<a class="a2a_button_twitter"></a>
<a class="a2a_button_whatsapp"></a>
<a class="a2a_button_telegram"></a>
<a class="a2a_button_google_gmail"></a>
<a class="a2a_button_pinterest"></a>
<a class="a2a_button_reddit"></a>
<a class="a2a_button_facebook"></a>
<a class="a2a_button_facebook_messenger"></a>
</div>
<script>
var a2a_config = a2a_config || {};
a2a_config.onclick = 1;
</script>
<script async src="https://static.addtoany.com/menu/page.js"></script>
<!-- AddToAny END -->