-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path6_Weighted_Scatterplots.Rmd
372 lines (299 loc) · 16.9 KB
/
6_Weighted_Scatterplots.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
---
title: "Creating plots in R using ggplot2 - part 6: weighted scatterplots"
author:
- Jodie Burchell
- Mauricio Vargas Sepúlveda
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, cache = FALSE, echo = FALSE, message = FALSE, warning = FALSE, tidy = FALSE}
knitr::opts_chunk$set(message = F, error = F, warning = F, comment = NA, fig.align = 'center', dpi = 96, fig.width=8, fig.height=5, tidy = F, cache.path = '6_Weighted_Scatterplots_cache/', fig.path = '6_Weighted_Scatterplots/')
```
This is the sixth tutorial in a series on using `ggplot2` I am creating with [Jodie Burchell](http://t-redactyl.github.io/). In this tutorial we will demonstrate some of the many options the `ggplot2` package has for creating and customising weighted scatterplots. These plots are also called 'balloon plots' or 'bubble plots'. We will use R's [airquality dataset](https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/airquality.html) in the `datasets` package. In order to reduce the complexity of these data a little, we will only be looking at the final three months in the dataset (July, August and September).
In this tutorial, we will work towards creating the weighted scatterplot below. We will take you from a basic scatterplot and explain all the customisations we add to the code step-by-step.
```{r wscatter_finalgraph, echo = FALSE, cache=TRUE}
library(ggplot2)
library(ggthemes)
library(extrafont)
library(plyr)
library(scales)
library(grid)
data(airquality)
aq_trim <- airquality[which(airquality$Month == 7 |
airquality$Month == 8 |
airquality$Month == 9), ]
aq_trim$Month <- factor(aq_trim$Month,
labels = c("July", "August", "September"))
fill = c("steelblue", "yellowgreen", "violetred1")
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Month)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)",
size = "Wind Speed (mph) ", fill = "Months ") +
scale_x_continuous(breaks = seq(1, 31, 5)) +
scale_size(range = c(1, 10)) +
scale_fill_manual(values = fill) +
theme(panel.border = element_rect(colour = "black", fill=NA, size=.5),
axis.text.x=element_text(colour="black", size = 9),
axis.text.y=element_text(colour="black", size = 9),
legend.position="bottom",
legend.direction="horizontal",
legend.box = "horizontal",
legend.key.size = unit(1, "cm"),
legend.key = element_blank(),
panel.grid.major = element_line(colour = "#d3d3d3"),
panel.grid.minor = element_blank(),
panel.border = element_blank(), panel.background = element_blank(),
plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
text=element_text(family="Tahoma"))
p6
```
The first thing to do is load in the data and the libraries, as below:
```{r wscatter_load_in_data, cache=TRUE}
library(ggplot2)
library(ggthemes)
library(extrafont)
library(plyr)
library(scales)
data(airquality)
```
We will then trim the data down to the final three months and turn the `Month` variable into a labelled factor variable. We end up with a new dataset called `aq_trim`.
```{r wscatter_trimming_data, cache=TRUE}
aq_trim <- airquality[which(airquality$Month == 7 |
airquality$Month == 8 |
airquality$Month == 9), ]
aq_trim$Month <- factor(aq_trim$Month,
labels = c("July", "August", "September"))
```
# Basic weighted scatterplot
Let's start really slowly by revisiting how to create a basic scatterplot. In order to initialise this plot we tell ggplot that `aq_trim` is our data, and specify that our x-axis plots the `Day` variable and our y-axis plots the `Ozone` variable. We then instruct ggplot to render this as a scatterplot by adding the `geom_point()` option.
```{r wscatter_1, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone)) +
geom_point()
p6
```
In order to turn this into a weighted scatterplot, we simply add the `size` argument to `ggplot(aes())`. In this case, we want to weight the points by the `Wind` variable.
```{r wscatter_2, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind)) +
geom_point()
p6
```
You can see we already have an interesting looking pattern, where days with higher wind speed tend to have lower ozone (or in other words, better air quality). Now let's make it beautiful!
# Changing the shape of the data points
Perhaps we want the data points to be a different shape than a solid circle. We can change these by adding the `shape` argument to `geom_point`. An explanation of the allowed arguments for shape are described in [this article](http://sape.inf.usi.ch/quick-reference/ggplot2/shape). In this case, we will use shape 21, which is a circle that allows different colours for the outline and fill.
```{r wscatter_3, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind)) +
geom_point(shape = 21)
p6
```
# Adjusting the axis scales
To change the x-axis tick marks, we use the `scale_x_continuous` option. Similarly, to change the y-axis we use the `scale_y_continuous` option. Here we will change the x-axis to every 5 days, rather than 10, and change the range from 1 to 31 (as 0 is not a valid value for this variable).
```{r wscatter_4, cache=TRUE}
p6 <- p6 + scale_x_continuous(breaks = seq(1, 31, 5))
p6
```
# Adjusting axis labels & adding title
To add a title, we include the option `ggtitle` and include the name of the graph as a string argument. To change the axis names we add `x` and `y` arguments to the `labs` command.
```{r wscatter_5, cache=TRUE}
p6 <- p6 + ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)")
p6
```
# Adjusting the colour palette
There are a few options for adjusting the colour. The most simple is to make every point one fixed colour. You can reference colours by name, with the full list of colours recognised by R [here](http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf). Let's try making the outline `mediumvioletred` and the fill `springgreen`.
```{r wscatter_6, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind)) +
geom_point(shape = 21, colour = "mediumvioletred", fill = "springgreen") +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)") +
scale_x_continuous(breaks = seq(1, 31, 5))
p6
```
You can change the colours using specific HEX codes instead. Here we have made the outline #000000 (black) and the fill "#40b8d0 (vivid cyan).
```{r wscatter_7, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind)) +
geom_point(shape = 21, colour = "#000000", fill = "#40b8d0") +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)") +
scale_x_continuous(breaks = seq(1, 31, 5))
p6
```
You can also change the colour of the data points according to the levels of another variable. This can be done either as a continuous gradient, or as a levels of a factor variable. Let's change the colour by the values of temperature:
```{r wscatter_8, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Temp)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)") +
scale_x_continuous(breaks = seq(1, 31, 5))
p6
```
We can change the gradient's colours by adding the `scale_fill_continuous` option. The `low` and `high` arguments specify the range of colours the gradient should transition between.
```{r wscatter_9, cache=TRUE}
p6 <-p6 + scale_fill_continuous(low = "plum1", high = "purple4")
p6
```
We can see that higher temperatures seem to have higher ozone levels.
Let's now change the colours of the data points by a factor variable, `Month`.
```{r wscatter_10, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Month)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)") +
scale_x_continuous(breaks = seq(1, 31, 5))
p6
```
Again, we can change the colours of these data points, this time using `scale_fill_manual`.
```{r wscatter_11, cache=TRUE}
fill = c("steelblue", "yellowgreen", "violetred1")
p6 <- p6 + scale_fill_manual(values = fill)
p6
```
# Adjusting the size of the data points
The default size of the the data points in a weighted scatterplot is mapped to the radius of the plots. If we want the data points to be proportional to the value of the weighting variable (e.g., a wind speed of 0 mph would have a value of 0), we need to use the `scale_size_area`.
```{r wscatter_12, cache=TRUE}
p6 <- p6 + scale_size_area(max_size = 10)
p6
```
For our graph, this makes the pattern for `Wind` a little hard to see. Another way to adjust the size of the data points is to use `scale_size` and specify a desired range.
```{r wscatter_13, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Month)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)") +
scale_x_continuous(breaks = seq(1, 31, 5)) +
scale_fill_manual(values = fill) +
scale_size(range = c(1, 10))
p6
```
# Adjusting legend position
To adjust the position of the legend from the default spot of right of the graph, we add the `theme` option and specify the `legend.position = "bottom"` argument. We can also change the legend shape using the `legend.direction = "horizontal"` argument.
```{r wscatter_14, cache=TRUE}
p6 <- p6 + theme(legend.position = "bottom", legend.direction = "horizontal")
p6
```
# Changing the legend titles
To change the titles of the two legends, we use the `labs` option. In order to tell ggplot2 exactly what legend you're referring to, just have a look in the `ggplot` option and see what argument you used to create the legend in the first place. In this case we used the `size` argument for "Wind" and `fill` for "Month", so we pass these to `labs` with our new titles.
```{r wscatter_15, cache=TRUE}
p6 <- p6 + labs(size = "Wind Speed (mph) ", fill = "Months ")
p6
```
# Creating horizontal legends
It looks a little awkward having the two titles sitting on top of each other, as well as taking up unnecessary space. To place the legends next to each other, we use the `legend.box = "horizontal"` argument in `theme`. Because the boxes around the legend keys aren't even in each of the legends, this means the legends don't align properly. To fix this, we change the box size around the legend keys using `legend.key.size`. We need to load in the `grid` package to get this argument to work.
```{r wscatter_16, cache=TRUE}
p6 <- p6 + theme(legend.box = "horizontal", legend.key.size = unit(1, "cm"))
p6
```
# Using the white theme
As explained in the previous posts, we can also change the overall look of the plot using themes. We'll start using a simple theme customisation by adding `theme_bw() ` after `ggplot()`. As you can see, we can further tweak the graph using the `theme` option, which we've used so far to change the legend.
```{r wscatter_17, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Month)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)",
size = "Wind Speed (mph) ", fill = "Months ") +
scale_x_continuous(breaks = seq(1, 31, 5)) +
scale_fill_manual(values = fill) +
scale_size(range = c(1, 10)) +
theme_bw() +
theme(legend.position="bottom", legend.direction="horizontal",
legend.box = "horizontal",
legend.key.size = unit(1, "cm"))
p6
```
# Creating an XKCD style chart
Of course, you may want to create your own themes as well. `ggplot2` allows for a very high degree of customisation, including allowing you to use imported fonts. Below is an example of a theme Mauricio was able to create which mimics the visual style of [XKCD](http://xkcd.com/). In order to create this chart, you first need to import the XKCD font, and load it into R using the `extrafont` package.
```{r wscatter_18, cache=TRUE}
fill <- c("#56B4E9", "#F0E442", "violetred1")
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Month)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)",
size = "Wind Speed (mph) ", fill = "Months ") +
scale_x_continuous(breaks = seq(1, 31, 5)) +
scale_fill_manual(values = fill) +
scale_size(range = c(1, 10)) +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
legend.position="bottom",
legend.direction="horizontal",
legend.box = "horizontal",
legend.key.size = unit(1, "cm"),
legend.key = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
plot.title=element_text(family="xkcd-Regular"),
text=element_text(family="xkcd-Regular"))
p6
```
# Using 'The Economist' theme
There are a wider range of pre-built themes available as part of the `ggthemes` package (more information on these [here](https://cran.r-project.org/web/packages/ggthemes/vignettes/ggthemes.html)). Below we've applied `theme_economist()`, which approximates graphs in the Economist magazine. It is also important that the font change argument inside `theme` is optional and it's only to obtain a more similar result compared to the original. For an exact result you need 'Officina Sans' which is a commercial font and is available [here](http://www.myfonts.com/fonts/itc/officina-sans/).
```{r wscatter_19, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Month)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)", size = "Wind Speed (mph) ", fill = "Months ") +
scale_x_continuous(breaks = seq(1, 31, 5)) +
scale_size(range = c(1, 10)) +
theme_economist() + scale_fill_economist() +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.title = element_text(size = 12),
legend.position="bottom",
legend.direction="horizontal",
legend.box = "horizontal",
legend.key.size = unit(1, "cm"),
legend.text = element_text(size = 10),
text = element_text(family = "OfficinaSanITC-Book"),
plot.title = element_text(family="OfficinaSanITC-Book"))
p6
```
# Using 'Five Thirty Eight' theme
Below we've applied `theme_fivethirtyeight()`, which approximates graphs in the nice [FiveThirtyEight](http://fivethirtyeight.com/) website. Again, it is also important that the font change is optional and it's only to obtain a more similar result compared to the original. For an exact result you need 'Atlas Grotesk' and 'Decima Mono Pro' which are commercial font and are available [here](https://commercialtype.com/catalog/atlas) and [here](https://www.myfonts.com/fonts/tipografiaramis/decima-mono-pro/).
```{r wscatter_20, cache=TRUE}
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Month)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)", size = "Wind Speed (mph) ", fill = "Months ") +
scale_x_continuous(breaks = seq(1, 31, 5)) +
scale_size(range = c(1, 10)) +
theme_fivethirtyeight() + scale_fill_fivethirtyeight() +
theme(axis.title = element_text(family="Atlas Grotesk Regular"),
legend.position="bottom",
legend.direction="horizontal",
legend.box = "horizontal",
legend.key.size = unit(1, "cm"),
legend.title=element_text(family="Atlas Grotesk Regular", size = 10),
legend.text=element_text(family="Atlas Grotesk Regular", size = 10),
plot.title=element_text(family="Atlas Grotesk Medium"),
text=element_text(family="DecimaMonoPro"))
p6
```
# Creating your own theme
As before, you can modify your plots a lot as `ggplot2` allows many customisations. Here we present our original result shown at the top of page.
```{r wscatter_21, cache=TRUE}
fill = c("steelblue", "yellowgreen", "violetred1")
p6 <- ggplot(aq_trim, aes(x = Day, y = Ozone, size = Wind, fill = Month)) +
geom_point(shape = 21) +
ggtitle("Air Quality in New York by Day") +
labs(x = "Day of the month", y = "Ozone (ppb)", size = "Wind Speed (mph) ", fill = "Months ") +
scale_x_continuous(breaks = seq(1, 31, 5)) +
scale_size(range = c(1, 10)) +
scale_fill_manual(values = fill) +
theme(panel.border = element_rect(colour = "black", fill=NA, size=.5),
axis.text.x=element_text(colour="black", size = 9),
axis.text.y=element_text(colour="black", size = 9),
legend.position="bottom",
legend.direction="horizontal",
legend.box = "horizontal",
legend.key.size = unit(1, "cm"),
legend.key = element_blank(),
panel.grid.major = element_line(colour = "#d3d3d3"),
panel.grid.minor = element_blank(),
panel.border = element_blank(), panel.background = element_blank(),
plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
text=element_text(family="Tahoma"))
p6
```