-
Notifications
You must be signed in to change notification settings - Fork 1
/
Lesson1.Rmd
416 lines (333 loc) · 11.6 KB
/
Lesson1.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
---
params:
lesson: "Lesson 1"
title: "Intro to plotting data in R with `ggplot`"
bookchapter_name: "Section 3.1.1"
bookchapter_section: "https://r4ds.had.co.nz/data-visualisation.html"
functions: "`?`, `str`, `glimpse`, `summary`, `table`, `min`, `max`, `ggplot`, `geom_point`, `geom_smooth`, `theme_minimal`, `theme_classic`, `theme_tufte`"
packages: "`tidyverse`, `ggplot2`, `dplyr`"
# end inputs ---------------------------------------------------------------
header-includes: \usepackage{float}
always_allow_html: yes
output:
html_document:
code_folding: show
code_download: true
---
```{r, setup, echo = FALSE, cache = FALSE, include = FALSE}
options(width=100)
knitr::opts_chunk$set(
eval = FALSE, # run all code
echo = TRUE, # show code chunks in output
tidy = TRUE, # make output as tidy
message = FALSE, # mask all messages
warning = FALSE, # mask all warnings
comment = "",
tidy.opts=list(width.cutoff=100), # set width of code chunks in output
size="small" # set code chunk size
)
```
\
<!-- install packages -->
```{r, load packages, eval=T, include=T, cache=F, message=F, warning=F, results='hide',echo=F}
packages <- c("ggplot2","ggthemes","dplyr","tidyverse","zoo","RColorBrewer","viridis","plyr")
if (require(packages)) {
install.packages(packages,dependencies = T)
require(packages)
# load tvthemes
# devtools::install_github("Ryo-N7/tvthemes")
}
lapply(packages,library,character.only=T)
```
<!-- ____________________________________________________________________________ -->
<!-- ____________________________________________________________________________ -->
<!-- ____________________________________________________________________________ -->
<!-- start body -->
# `r paste0(params$lesson,": ",params$title)`
\
Functions for `r params$lesson`
`r params$functions`
\
Packages for `r params$lesson`
`r params$packages`
\
# Agenda
[Data visualisation in `R` for Data Science, `r params$bookchapter_name`](`r params$bookchapter_section`).
<!-- end yaml template------------------------------------------------------- -->
* Intro to the `R`environment (IDE)
* Loading packages, e.g. `tidyverse`
* Using built-in `R` data: the `mpg` dataset
* Using ggplot with the built-in data set (to make scatterplots)
* Modifying plot aesthetics
* Reading in outside data: Airbnb data
* Plotting Airbnb data with ggplot
\
# Intro to the `R` environment (IDE)
The `RStudio` integrated development environment (IDE) and what you can do with it.
\
<!-- ----------------------- image --------------------------- -->
<div align="center">
<img src="img/rstudio1.jpg" style=width:100%>
</div>
<!-- ----------------------- image --------------------------- -->
\
A more complete example of what you can acheive with the interface.
\
<!-- ----------------------- image --------------------------- -->
<div align="center">
<img src="img/rstudio2.jpg" style=width:100%>
</div>
<!-- ----------------------- image --------------------------- -->
\
# Loading packages, e.g. `tidyverse`
How to load packages in `R`.
```{r}
install.packages("tidyverse") # install package
library(tidyverse) # load the package library
require(tidyverse) # same as library
# We are typing in an R Script. Things with # in front make them comments and notes to ourselves
# Command Return to execute the line/ "run the code"
```
\
# Using built-in `R` data: the `mpg` dataset
[Section 3.2.1](https://r4ds.had.co.nz/data-visualisation.html#the-mpg-data-frame)
We'll use a built-in tidyverse dataset called `mpg` with data about cars and gas-mileage.
```{r}
mpg
# run help page with '?'
?mpg
```
* This is a tibble (data frame) that we've "printed" out. It's like R's version of an excel spreadsheet, but much better.
* A tibble will show us the first 10 rows, rows containing the data, column names, and the class of data within each column, such as numeric, integer, or character.
## Summarising data
```{r}
str(mpg) # structure of data
glimpse(mpg) # preview of data
summary(mpg) # basic summary stats
table(mpg$manufacturer) # counts of each column
head(mpg) # visualise first 6 rows of data
tail(mpg,10) # visualise last 10 (or N) rows of data
names(mpg) # get column names
class(mpg) # class of data frame
class(mpg$manufacturer) # class of data column
mpg$displ # print a column
mpg$hwy # print a column
```
\
# Creating a plot with `ggplot`
[Section 3.2.2](https://r4ds.had.co.nz/data-visualisation.html#creating-a-ggplot)
* `ggplot()` Creates a coordinate system for us--basically an empty graph.
* `geom_point()` Adds a "layer", e.g. geom_point (but there are many for different kinds of graphs).
Plot two of the data columns
```{r, eval = T}
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
```
\
Changing the data column inputs for the **x** and **y** axis of the plot
```{r, eval = T}
ggplot(data = mpg) +
geom_point(mapping = aes(x = class, y = drv))
```
\
Assign data to variables to create dynamic inputs
```{r, eval = T}
my_data <- mpg # create own variable using a name of your choice
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy))
```
\
## Themes
Change plot style. Link for more [ggplot themes](https://www.datanovia.com/en/blog/ggplot-themes-gallery/).
```{r, eval = T}
require(ggthemes)
# classic theme
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy)) +
theme_minimal()
# minimal theme
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy)) +
theme_tufte()
# assign theme to variable
my_theme <- theme_classic()
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy)) +
my_theme # apply your chosen theme
```
\
# Aesthetic mapping
[Section 3.3](https://r4ds.had.co.nz/data-visualisation.html#aesthetic-mappings)
`colour`. Change the colour of the data points.
`size`. Change the size of the data points.
`alpha`. Change the transparency of the data points.
## Colour
Colour by colour name.
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy), colour = "light blue") +
my_theme
```
\
Colour by a [hex code](https://htmlcolorcodes.com/color-picker/) in quotes.
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy), colour = "#BB5C42") +
my_theme
```
\
colour by data column
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy, colour = class)) +
my_theme
```
\
Inside versus outside the `aes`
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy, colour = "blue")) +
my_theme
```
\
## Size
Size by integer
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy, size = 5)) +
my_theme
```
\
Size by data column
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy, size = class)) +
my_theme
```
\
We get a warning, but this is okay.
\
## Transparency
```{r, eval = T}
# map classe column to different transparencies
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy, alpha = class)) +
my_theme
```
\
## Shape
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy, shape = class)) +
my_theme
```
\
Any warnings? Yes, because shape maxes out at six levels.
\
## Manually changing aesthetic properties
But we can *set* the aesthetic properties manually, instead of having ggplot do the scaling automatically. For example, we can make our ggplot points all blue like this. This time, putting colour OUTSIDE the `aes` argument.
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy), colour = "blue") +
my_theme
```
\
Using colour both inside and outside the aes
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy, colour = class), colour = "#AE42BB") +
my_theme
```
\
**The inner one is overridden.**
\
Putting it all together as a snapshot of what's possible
```{r, eval = T}
ggplot(data = my_data) +
geom_point(mapping = aes(x = displ, y = hwy, colour = class, size = class, alpha = class)) +
my_theme
```
## Aesthetics you can manually set
* The name of a colour as a character string.
* The size of a point in mm.
* The shape of a point as a number, as shown in Figure 3.1.
<!-- ----------------------- image --------------------------- -->
<div align="center">
<img src="img/shapes.png" style=width:100%>
</div>
<!-- ----------------------- image --------------------------- -->
\
`R` has 25 built in shapes that are identified by numbers. There are some seeming duplicates: for example, 0, 15, and 22 are all squares. The difference comes from the interaction of the `colour` and `fill` aesthetics. The hollow shapes (0--14) have a border determined by `colour`; the solid shapes (15--18) are filled with `colour`; the filled shapes (21--24) have a border of `colour` and are filled with `fill`.
\newpage
# Further plotting examples
[Section 3.3.1](https://r4ds.had.co.nz/data-visualisation.html#exercises-1)
The online reference contains further examples of how to visualise your data.
# Reading in outside data: NYC Airbnb data
```{r, eval = T, echo = F}
library(tidyverse) # includes package "readr"
# All Airbnb data (106 cols)
url <- "http://data.insideairbnb.com/united-states/ny/new-york-city/2021-04-07/data/listings.csv.gz"
nyc_full <- read_csv(url) # reads in data
head(nyc_full)
```
\
Using a smaller dataset
```{r, eval = T, results="hide"}
# smaller csv file (16 cols)
url <- "http://data.insideairbnb.com/united-states/ny/new-york-city/2021-04-07/data/listings.csv.gz"
nyc <- read_csv(url)
nyc <- nyc[nyc$id < 20000,] # get smaller subet of data
length(nyc$id) # print length of 'id' column
head(nyc)
```
\
# Plotting AirBnB data with ggplot
Using the above plotting functions to visualise the AirBnB data
```{r, eval = T}
# plot neighborhood_group vs price
ggplot(data = nyc) +
geom_point(mapping = aes(x = neighbourhood_group_cleansed, y = price, colour =
neighbourhood_group_cleansed), shape = 21, stroke = 1) +
my_theme
```
```{r, eval=T}
# plot minimum_nights vs price
ggplot(data = nyc) +
geom_point(mapping = aes(x = minimum_nights, y = price,
colour = neighbourhood_group_cleansed), shape = 20, size = 3, stroke = 1) +
my_theme
```
```{r, eval=T}
# availability_365 vs price
ggplot(data = nyc) +
geom_point(mapping = aes(x = availability_365, y = price,
colour = neighbourhood_group_cleansed), shape = 21, stroke = 1) +
my_theme
```
```{r, eval=T}
# plot longitude vs price
ggplot(data = nyc) +
geom_point(mapping = aes(x = longitude, y = price,
colour = neighbourhood_group_cleansed), shape = 21, stroke = 1) +
my_theme
```
Try your own plot using the other variables in the dataset
```{r}
# plot neighborhood_group vs price
names(airbnb)
glimpse(airbnb)
my_data <- NULL
x <- NULL
y <- NULL
colour <- NULL
shape <- NULL
stroke <- NULL
```
```{r, echo=F}
ggplot(data = my_data) +
geom_point(mapping = aes(x = x, y = y, colour = colour), shape = shape, stroke = stroke)
```
<!-- end body -->
<!-- ____________________________________________________________________________ -->
<!-- ____________________________________________________________________________ -->
<!-- ____________________________________________________________________________ -->