forked from jtr13/EDAV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboxplot.Rmd
executable file
·161 lines (120 loc) · 7.84 KB
/
boxplot.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
# Chart: Boxplot {#box}

## Overview
This section covers how to make boxplots.
## tl;dr
I want a nice example and I want it NOW!
Here's a look at the weights of newborn chicks split by the feed supplement they received:
```{r tldr-show-plot, echo=FALSE}
library(datasets) # data
library(ggplot2) # plotting
# reorder supplements
supps <- c("horsebean", "linseed", "soybean", "meatmeal", "sunflower", "casein")
# boxplot by feed supplement with jitter layer
ggplot(chickwts, aes(x = factor(feed, levels = supps),
y = weight)) +
# plotting
geom_boxplot(fill = "#cc9a38", color = "#473e2c") +
geom_jitter(alpha = 0.2, width = 0.1, color = "#926d25") +
# formatting
ggtitle("Casein Makes You Fat?!",
subtitle = "Boxplots of Chick Weights by Feed Supplement") +
labs(x = "Feed Supplement", y = "Chick Weight (g)", caption = "Source: datasets::chickwts") +
theme(plot.title = element_text(face = "bold")) +
theme(plot.subtitle = element_text(face = "bold", color = "grey35")) +
theme(plot.caption = element_text(color = "grey68"))
```
And here's the code:
```{r tldr-code, eval=FALSE}
library(datasets) # data
library(ggplot2) # plotting
# reorder supplements
supps <- c("horsebean", "linseed", "soybean", "meatmeal", "sunflower", "casein")
# boxplot by feed supplement with jitter layer
ggplot(chickwts, aes(x = factor(feed, levels = supps),
y = weight)) +
# plotting
geom_boxplot(fill = "#cc9a38", color = "#473e2c") +
geom_jitter(alpha = 0.2, width = 0.1, color = "#926d25") +
# formatting
ggtitle("Casein Makes You Fat?!",
subtitle = "Boxplots of Chick Weights by Feed Supplement") +
labs(x = "Feed Supplement", y = "Chick Weight (g)", caption = "Source: datasets::chickwts") +
theme(plot.title = element_text(face = "bold")) +
theme(plot.subtitle = element_text(face = "bold", color = "grey35")) +
theme(plot.caption = element_text(color = "grey68"))
```
For more info on this dataset, type `?datasets::chickwts` into the console.
## Simple examples
Okay...*much* simpler please.
Let's use the `airquality` dataset from the `datasets` package:
```{r simple-example-data}
library(datasets)
head(airquality, n = 5)
```
### Boxplot using base R
```{r base-r}
# plot data
boxplot(airquality, col = 'lightBlue', main = "Base R Boxplots of airquality")
```
Boxplots with Base R are super easy. Like [histograms](histo.html), boxplots only need the data. In this case, we passed a dataframe with six variables, so it made separate boxplots for each variable. You may not want to create boxplots for every variable, in which case you could specify the variables individually or use [`filter`](https://www.rdocumentation.org/packages/dplyr/versions/0.7.5/topics/filter){target="_blank"} from the [`dplyr`](https://www.rdocumentation.org/packages/dplyr/versions/0.7.5){target="_blank"} package.
### Boxplot using ggplot2
```{r ggplot}
# import ggplot
library(ggplot2)
# plot data
g1 <- ggplot(stack(airquality), aes(x = ind, y = values)) +
geom_boxplot(fill = "lightBlue") +
# extra formatting
labs(x = "") +
ggtitle("ggplot2 Boxplots of airquality")
g1
```
`ggplot2` requires data to be mapped to the `x` and `y` aesthetics. Here we use the `stack` function to combine each column of the `airquality` dataframe. Reading the documentation for the `stack` function (`?utils::stack`), we see the new stacked dataframe has two columns: `values` and `ind`, which we use to create the boxplots. **Notice**: `ggplot2` warns us that it is ignoring "non-finite values", which are the NA's in the dataset.
## Theory
Here's a quote by Hadley Wickham that sums up boxplots nicely:
>The boxplot is a compact distributional summary, displaying less detail than a histogram or kernel density, but also taking up less space. Boxplots use robust summary statistics that are always located at actual data points, are quickly computable (originally by hand), and have no tuning parameters. They are particularly useful for comparing distributions across groups. - Hadley Wickham
>
Another important use of the boxplot is in showing outliers. A boxplot shows how much of an outlier a data point is with quartiles and fences. Use the boxplot when you have data with outliers so that they can be exposed. What it lacks in specificity it makes up with its ability to clearly summarize large data sets.
* For more info about boxplots and continuous variables, check out [Chapter 3](http://www.gradaanwr.net/content/03-examining-continuous-variables/){target="_blank"} of the textbook.
## When to use
Boxplots should be used to display *continuous variables*. They are particularly useful for identifying outliers and comparing different groups.
*Aside*: Boxplots may even help you [convince someone you are their outlier](https://xkcd.com/539/){target="_blank"} (If you like it when people over-explain jokes, [here is why that comic is funny](https://www.explainxkcd.com/wiki/index.php/539:_Boyfriend){target="_blank"}.).
## Considerations
### Flipping orientation
Often you want boxplots to be horizontal. Super easy to do: just tack on `coord_flip()`:
```{r flip-boxplot}
# g1 plot from above (5.3.2)
g1 + coord_flip()
```
### NOT for categorical data
Boxplots are great, but they do NOT work with categorical data. Make sure your variable is continuous before using boxplots. Here's an example of what *not* to do:
```{r bad-boxplots, message=FALSE}
library(likert) # data
library(dplyr) # data manipulation
# load/format data
data(pisaitems)
pisa <- pisaitems[1:100, 2:7] %>%
dplyr::mutate_all(as.integer) %>%
dplyr::filter(complete.cases(.))
# create theme
theme <- theme(plot.title = element_text(face = "bold")) +
theme(plot.subtitle = element_text(face = "bold", color = "grey35")) +
theme(plot.caption = element_text(color = "grey68"))
# create plot
plot <- ggplot(stack(pisa), aes(x = ind, y = values)) +
geom_boxplot(fill = "#9B3535") +
ggtitle("Don't Plot Boxplots of Categorical Variables Like This",
subtitle = "...seriously don't. Here, I'll make it red so it looks scary:") +
labs(x = "Assessment Code", y = "Values", caption = "Source: likert::pisaitems")
# bad boxplot
plot + theme
```
## External resources
- Tukey, John W. 1977. [*Exploratory Data Analysis.*](https://clio.columbia.edu/catalog/136422){target="_blank"} Addison-Wesley. (Chapter 2): the primary source in which boxplots are first presented.
- [DataCamp: Quick Exercise on Boxplots](https://campus.datacamp.com/courses/helsinki-open-data-science/logistic-regression?ex=7){target="_blank"}: a simple example of making boxplots from a dataset.
- [Article on boxplots with ggplot2](http://t-redactyl.io/blog/2016/04/creating-plots-in-r-using-ggplot2-part-10-boxplots.html){target="_blank"}: An excellent collection of code examples on how to make boxplots with `ggplot2`. Covers layering, working with legends, faceting, formatting, and more. If you want a boxplot to look a certain way, this article will help.
- [Boxplots with plotly package](https://plot.ly/ggplot2/box-plots/){target="_blank"}: boxplot examples using the `plotly` package. These allow for a little interactivity on hover, which might better explain the underlying statistics of your plot.
- [ggplot2 Boxplot: Quick Start Guide](http://www.sthda.com/english/wiki/ggplot2-box-plot-quick-start-guide-r-software-and-data-visualization){target="_blank"}: Article from [STHDA](http://www.sthda.com/english/){target="_blank"} on making boxplots using ggplot2. Excellent starting point for getting immediate results and custom formatting.
- [ggplot2 cheatsheet](https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf){target="_blank"}: Always good to have close by.
- [Hadley Wickhan and Lisa Stryjewski on boxplots](http://vita.had.co.nz/papers/boxplots.pdf){target="_blank"}: good for understanding basics of more complex boxplots and some of the history behind them.