-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2B-DescriptiveStatistics.qmd
More file actions
221 lines (160 loc) · 6.59 KB
/
Copy path2B-DescriptiveStatistics.qmd
File metadata and controls
221 lines (160 loc) · 6.59 KB
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
---
output: html_document
editor_options:
chunk_output_type: console
---
```{r, include=FALSE}
set.seed(42)
```
# Plotting and describing data
Before knowing how to plot something, you should know what you want to plot:
| Scenario | Which plot | R command |
|------------------------|------------------------|------------------------|
| Numeric | Histogram or boxplot | `hist(num)` and `boxplot(num)` |
| Numeric with numeric | Scatterplot | `plot(num~num)` |
| Numeric with categorical | Boxplot | `boxplot(num~cat)` |
| Categorical with categorical | mosaicplot or grouped barplot | `mosaicplot(table(cat, cat))` or `barplot(data, beside=TRUE)` |
::: column-margin
Here is a [website](https://www.data-to-viz.com/) with a decision tree about when to choose which plot.
:::
Once you know what you want to plot, there are lot of websites that will show you the respective R code. One important consideration, however: there are at least two popular ways of doing R graphs:
- **base R**: The `graphics` package is automatically shipped with the R language and is the default plotting package in R. It produces basic scientific plots (no unnecessary information)
- `ggplot2` is a plotting package where the default plots are more visually appealling, it belongs to the `tidyverse`, which is a group of packages with a different grammar for coding in R.
<!-- {{< video https://youtu.be/maFw5qXyCwg >}} -->
<!-- {{< video https://youtu.be/HeqHMM4ziXA >}} -->
You should probably get to know both types, but we recommend to **start with base R**. We are just saying this so that you are not confused, because a lot of the examples will also show you ggplot code. Here some useful links:
- A few [simple graphs in base R](https://www.statmethods.net/graphs/index.html).
- R code for the [most common graphics](https://www.r-graph-gallery.com/index.html) (with a ggplot2 tendecy).
- R code [graph tutorials](https://r-coder.com/r-graphs/).
::: column-margin
Thinking about how to do [good figures](https://www.cedricscherer.com/2019/05/17/the-evolution-of-a-ggplot-ep.-1/).
:::
## Plotting ONE variable
### Numerical variable - Histogram and Boxplot
- The histogram plots the frequency of the values of a numerical variable with bins (otherwise each unique value will appear only once, the range will be cut in n elements). The number of bins is automatically inferred by the function but can be also changed by the user
- The boxplot plots the distribution of a numerical variable based on summary statistics (the quantiles). The boxplot is particular useful for comparing/contrasting a numerical with a categorical variable (see below)
::: column-margin
In the base R code we introduced `par()` before plotting to create a panel with the plots side by side. In ggplot2 this is done with the package `ggpubr` (or `patchwork`).
:::
::: panel-tabset
### Base R
```{r}
par(mfrow = c(1,2)) # number of plots, one row, two columns
hist(iris$Sepal.Length,
main = "Histogram", # title
xlab = "Sepal.Length",
ylab = "Frequency",
las = 1) # rotation of x and y values (las = 1, all of them should be horizontal)
boxplot(iris$Sepal.Length,
main = "Boxplot", # title
ylab = "Values")
```
### ggplot2
```{r}
library(ggplot2)
library(ggpubr)
plt1 =
ggplot(iris, aes(x = Sepal.Length)) +
geom_histogram(bins = 8,col="white") + # same number of bins from baseR
ggtitle("Histogram") +
xlab("Sepal.Length") +
ylab("Frequency") +
theme_bw() # scientific theme (white background)
plt2 =
ggplot(iris, aes(y = Sepal.Length)) +
geom_boxplot() +
ggtitle("Boxplot") +
ylab("Values") +
theme_bw()
ggarrange(plt1, plt2, ncol = 2L, nrow = 1L)
```
:::
### Categorical variable - Barplot
```{r}
str(mtcars)
counts = table(mtcars$cyl)
counts
```
::: panel-tabset
### Base R
```{r}
barplot(counts,
main = "Barplot of Cyl",
ylab = "Number of occurrences",
xlab = "Cyl levels",
col = "#4488AA")
```
### ggplot2
```{r}
ggplot(mtcars, aes(x = cyl)) +
geom_bar(fill = "#4488AA") +
ggtitle("Barplot of Cyl") +
xlab("Number of occurrences") +
ylab("Cyl levels") +
theme_bw()
```
:::
## Plotting TWO variables
The general idea of plotting is to look for correlations / associations between variables, i.e. is there a non-random pattern between the two variables.
### Numerical vs numerical variable - Scatterplot
::: panel-tabset
### Base R
```{r}
# Scatterplot
par(mfrow = c(1,2))
plot(airquality$Solar.R, airquality$Ozone)
# plot(Ozone ~ Solar.R, data = airquality) #the same
# different symbol for each month
plot(Ozone ~ Solar.R, data = airquality, pch = Month)
```
::: column-margin
The **formula syntax** can also be used for plot functions in base R.
:::
We can also add other objects such as lines to our existing plot:
```{r}
par(mfrow = c(1,1))
plot(Ozone ~ Solar.R, data = airquality)
abline(h = 50)
```
### ggplot2
```{r,warning=F}
plt1 = ggplot(airquality, aes(x = Solar.R, y = Ozone)) +
geom_point() +
theme_bw()
plt2 = ggplot(airquality, aes(x = Solar.R, y = Ozone,
shape = as.factor(Month))) +
geom_point(show.legend = F) +
theme_bw()
ggarrange(plt1, plt2, ncol = 2L, nrow = 1L)
```
:::column-margin
I "turned off" the legend in plot 2 to be similar to base R plot. Try with `show.legend = T` to see the legend. Also, I had to convert `Month` to a factor to get different shapes.
:::
We can also add other objects such as lines to our existing plot:
```{r}
ggplot(airquality, aes(x = Solar.R, y = Ozone)) +
geom_point(shape = airquality$Month) +
geom_abline(intercept = 50, slope = 0) +
theme_bw()
```
:::
### Categorical vs numerical variable - Boxplot
Often we have a numerical variable (e.g. weight/fitness) and a categorical vairable that tells us the group of the observation (e.g. control or treatment). To compare visually now the distributions of the numerical variable between the levels of the grouping variable, we can use a boxplot
::: panel-tabset
### Base R
```{r, warning=F}
boxplot(mpg ~ cyl, mtcars, notch=TRUE) # formula notation
# boxplot(x = mtcars$cyl, y = mtcars$mpg) # the same
```
### ggplot2
```{r,warning=F}
ggplot(mtcars, aes(y = mpg, group = cyl)) +
geom_boxplot(notch=TRUE) +
theme_bw()
```
:::
::: {.callout-tip appearance="default"}
# Hint:
The `notch` argument adds a notch to the boxplot, which gives a visual indication of the confidence interval around the median. If the notches of two boxes do not overlap, it suggests that the medians are significantly different at the 5% significance level.
Try `notch = F` and see what you get.
:::