-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChapter9.qmd
458 lines (396 loc) · 14 KB
/
Chapter9.qmd
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
---
title: "Chapter 9"
subtitle: "Arranging Plots"
author: "Aditya Dahiya"
date: "2023-12-21"
format:
html:
code-fold: true
code-copy: hover
code-link: true
execute:
echo: true
warning: false
error: false
cache: true
filters:
- social-share
share:
permalink: "https://aditya-dahiya.github.io/ggplot2book3e/Chapter9.html"
description: "Solutions Manual (and Beyond) for ggplot2: Elegant Graphics for Data Analysis (3e)"
twitter: true
facebook: true
linkedin: true
email: true
mastodon: true
editor_options:
chunk_output_type: console
bibliography: references.bib
---
::: {.callout-note appearance="minimal"}
This chapter does not have any exercises. Instead, we practice arranging plots using the `patchwork` package [@patchwork] and [data](https://www.kaggle.com/datasets/saadharoon27/diwali-sales-dataset) on [Diwali Sales](https://github.com/rfordatascience/tidytuesday/blob/master/data/2023/2023-11-14/readme.md) from India, initially presented as a part of [#TidyTuesday](https://github.com/rfordatascience/tidytuesday/tree/master?tab=readme-ov-file#about-tidytuesday).
:::
## Libraries and Data
```{r}
#| label: setup
#| code-fold: false
#| message: false
#| error: false
#| warning: false
library(tidyverse) # tidy tools data wrangling
library(ggtext) # text into ggplot2
library(sf) # maps and plotting
library(here) # files location and loading
library(showtext) # Using Fonts More Easily in R Graphs
library(ggimage) # Using images in ggplot2
library(rvest) # Get states population data
library(fontawesome) # Social Media icons
library(ggtext) # Markdown Text in ggplot2
library(patchwork) # For combining plots
```
```{r}
#| message: false
#| error: false
#| warning: false
# Loading the data
diwali <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-11-14/diwali_sales_data.csv') |>
janitor::clean_names()
india_map <- st_read(here("data", "india_map", "India_State_Boundary.shp")) |>
mutate(state = str_to_title(State_Name),
.keep = "unused")
# Getting population Data from web scraping
state_pop <- rvest::read_html("https://www.indiacensus.net/") |>
html_nodes("table")
state_pop <- state_pop[1] |>
html_table()
state_pop <- state_pop[[1]] |>
janitor::clean_names() |>
select(2, 4) |>
rename(
state = state_name,
population = estimated_population_in_2023
)
state_pop <- state_pop |>
mutate(population = parse_number(population))
# Correct names for some states in india_map
india_map <- india_map |>
mutate(state = case_when(
state == "Tamilnadu" ~ "Tamil Nadu",
state == "Chhattishgarh" ~ "Chhattisgarh",
state == "Telengana" ~ "Telangana",
state == "Jammu And Kashmir" ~ "Jammu & Kashmir",
state == "Andaman & Nicobar" ~ "Andaman & Nicobar Islands",
state == "Daman And Diu And Dadra And Nagar Haveli" ~ "Dadra and Nagar Haveli",
.default = state
))
# Number of customers per capita and Avg. Purchase per customer
df1 <- diwali |>
count(state, sort = TRUE) |>
full_join(state_pop) |>
mutate(cust_m_pop = 1000000 * n / population) |>
arrange(desc(cust_m_pop)) |>
rename(customers = n) |>
select(state, customers, cust_m_pop)
df2 <- diwali |>
group_by(state) |>
summarise(purchase = sum(amount, na.rm = TRUE)) |>
full_join(df1) |>
mutate(purc_cust = purchase / customers) |>
select(state, cust_m_pop, purc_cust) |>
mutate(
state = case_when(
state == "Jammu and Kashmir" ~ "Jammu & Kashmir",
state == "Orissa" ~ "Odisha",
.default = state)
)
mapdf <- df2 |>
full_join(india_map, relationship = "many-to-many") |>
# Simplifying geometry to drastically reduce plotting time
mutate(
geometry = st_simplify(geometry,
preserveTopology = FALSE,
dTolerance = 1000)
)
```
## **9.1 Laying out plots side by side**
Starting by defining some basic parameters, colours and annotations for the final plot
```{r}
# Load fonts
font_add_google("Pragati Narrow")
font_add_google("Pacifico")
font_add_google("Roboto")
showtext_auto()
body_font <- "Roboto" # Font for plot legends, body etc.
title_font <- "Pacifico" # Font for titles, subtitles
caption_font <- "Pragati Narrow" # Font for the caption
# Define colours
map1_col = c("yellow", # Colours for Chloropleth g1
"red")
map2_col = c("#cdeff7", # Colours for Chloropleth g2
"#1f76f0")
ts = 45 # Text Size
bg_col <- "white" # Background Colour
text_col <- "black" # Colour for the text
text_hil <- "red" # Colour for highlighted text
# Add text to plot
plot_title <- "Diwali Sales: Insights"
plot_subtitle <- "#TidyTuesday. Insights about the Diwali sales data."
sysfonts::font_add(family = "Font Awesome 6 Brands",
regular = here::here("docs", "Font Awesome 6 Brands-Regular-400.otf"))
github <- ""
github_username <- "aditya-dahiya"
xtwitter <- ""
xtwitter_username <- "@adityadahiyaias"
mastodon <- ""
mastodon_username <- "@adityadahiya@mastodon.social"
social_caption <- glue::glue(
"<span style='font-family:\"Font Awesome 6 Brands\";'>{github};</span> <span style='color: #000000'>{github_username} </span>
<span style='font-family:\"Font Awesome 6 Brands\";'>{xtwitter};</span> <span style='color: #000000'>{xtwitter_username}</span>"
)
plot_caption <- paste0("**Data**: kaggle.com<br>", social_caption)
```
The first plot `g1` (as shown in @fig-g1) shows map of India, with number of customers (per million population) from different states in the Data-Set.
```{r}
#| label: fig-g1
#| fig-cap: "Map of India with geom_sf() and geom_sf_text()"
#| fig-height: 7
#| fig-asp: 1
g1 <- mapdf |>
ggplot(aes(fill = cust_m_pop,
geometry = geometry,
label = state)) +
geom_sf() +
geom_sf_text(aes(alpha = !is.na(cust_m_pop)),
size = ts/15) +
coord_sf() +
scale_fill_continuous(low = map1_col[1],
high = map1_col[2],
na.value = bg_col,
trans = "log10") +
scale_alpha_discrete(range = c(0, 1)) +
guides(alpha = "none", fill = "colorbar") +
ggthemes::theme_map() +
labs(fill = "Customer Numbers\n(per mil. pop.)",
subtitle = "Customer numbers (per million population)") +
theme(plot.subtitle = element_text(size = ts/3,
family = body_font,
hjust = 0.5),
legend.text = element_text(size = ts/6,
family = body_font),
legend.title = element_text(size = ts/6,
family = body_font,
vjust = 0.5),
legend.position = "right",
legend.background = element_rect(fill = NULL),
legend.key.width = unit(2, "mm"))
g1
```
The second plot `g2` (as shown in @fig-g2) shows map of India, with average spending per customer in the Diwali Sales dataset from different states.
```{r}
#| label: fig-g2
#| fig-cap: "Using geom_sf and geom_sf_text to plot map with average customer spending"
#| fig-height: 7
#| fig-asp: 1
g2 <- mapdf |>
ggplot(aes(fill = purc_cust,
geometry = geometry,
label = state)) +
geom_sf() +
geom_sf_text(aes(alpha = !is.na(purc_cust)),
size = ts/15) +
coord_sf() +
scale_fill_continuous(low = map2_col[1],
high = map2_col[2],
na.value = bg_col,
labels = scales::label_comma(prefix = "Rs."),
breaks = c(8000, 10000)) +
scale_alpha_discrete(range = c(0, 1)) +
guides(alpha = "none", fill = "colorbar") +
ggthemes::theme_map() +
labs(fill = "Average Customer\nSpending (Rs.)",
subtitle = "Average customer spending (in Rupees)") +
theme(plot.subtitle = element_text(size = ts/3,
family = body_font,
hjust = 0.5),
legend.text = element_text(size = ts/6,
family = body_font),
legend.title = element_text(size = ts/6,
family = body_font,
vjust = 0.5),
legend.position = "right",
legend.background = element_rect(fill = NULL),
legend.key.width = unit(2, "mm"))
g2
```
Now, we lay the two plots side by side using `patchwork`: —
```{r}
#| label: fig-p1
#| fig-cap: "Using patchwork to combine two plots"
#| fig-width: 10
g1 + g2 +
plot_layout(guides = "collect") &
plot_annotation(
title = "Diwali Sales Data",
caption = "Source: #TidyTuesday, kaggle.com"
) &
theme(
plot.title = element_text(hjust = 0.5,
size = ts/2),
plot.caption = element_text(hjust = 0.5,
size = ts/5)
)
```
Another @fig-g3 shows the age distribution of customers in the data-set: —
```{r}
#| label: fig-g3
#| fig-cap: "Age distribution of the customers in the Diwali Dataset"
g3 <- diwali |>
count(age_group) |>
mutate(fill_var = age_group == "26-35") |>
ggplot(aes(x = n, y = age_group, fill = fill_var)) +
geom_col() +
labs(subtitle = "Maximum customers are aged 26-35",
y = "Customer Age Group",
x = "Number of customers") +
scale_x_continuous(labels = scales::label_number_si()) +
scale_fill_manual(values = c("grey", "orange")) +
cowplot::theme_minimal_vgrid() +
theme(axis.ticks.y = element_blank(),
panel.grid = element_line(linetype = 2),
axis.line.y = element_blank(),
panel.border = element_blank(),
plot.subtitle = element_text(hjust = 0.5,
size = ts/2),
axis.text = element_text(size = ts/4),
axis.title = element_text(ts/3),
legend.position = "none")
g3
```
Another @fig-g4 shows a heat-map of the products sold category-wise in different states from the data-set: —
```{r}
#| label: fig-g4
#| fig-cap: "A heat map using geom_tile() and geom_text()"
# Create ordering of groups
st_vec <- diwali |>
count(state, sort = TRUE) |>
pull(state) |>
rev()
pr_vec <- diwali |>
count(product_category, sort = TRUE) |>
pull(product_category)
g4 <- diwali |>
count(state, product_category, wt = orders, sort = TRUE) |>
mutate(
state = fct(state, levels = st_vec),
product_category = fct(product_category, levels = pr_vec)
) |>
ggplot(aes(y = state, x = product_category, fill = n)) +
geom_tile(col = "white") +
geom_text(aes(label = n), size = ts/18) +
scale_fill_gradient(low = "white",
high = "red",
na.value = "white",
trans = "log2",
breaks = c(1, 10, 50, 200, 500)) +
labs(x = NULL, y = NULL,
fill = "Number of products sold",
subtitle = "Certain items are more popular in some states") +
theme_minimal() +
theme(panel.grid = element_blank(),
axis.text.x = element_text(angle = 90,
hjust = 1),
legend.position = "right",
legend.title = element_text(angle = 90,
hjust = 0,
vjust = 1),
axis.text = element_text(size = ts/4),
plot.subtitle = element_text(size = ts/4))
g4
```
Combining the two @fig-g3 and @fig-g4 using `patchwork`: —
```{r}
#| label: fig-p2
#| fig-cap: "Combining plots using patchwork"
#| fig-width: 10
g3 + g4 +
plot_layout(design = "
ABB
ABB") +
plot_annotation(
title = "Insights from Diwali Sales Data",
tag_levels = "I",
tag_prefix = "Figure "
) &
theme(
plot.subtitle = element_text(hjust = 0,
size = ts/4),
plot.title = element_text(hjust = 0.5,
size = ts/1.5),
plot.tag.position = "top",
plot.tag = element_text(face = "italic",
size = ts/5)
)
```
## **9.2 Arranging plots on top of each other**
The @fig-inset1 shows the use of `inset_element()` to depict arranging plots on top of one-another using `patchwork`.
```{r}
#| label: fig-inset1
#| fig-cap: "A figure with inset horizontal bar plot on bottom-right corner using inset_element()"
#| fig-height: 7
g3inset <-
g3 +
labs(subtitle = NULL) +
theme(
axis.title = element_text(size = ts/5),
axis.text = element_text(size = ts/6),
plot.background = element_rect(fill = "white")
)
g1 +
theme(
legend.position = "bottom",
legend.key.width = unit(10, "mm"),
legend.key.height = unit(2, "mm")
) +
inset_element(
g3inset,
top = 0.3,
bottom = 0,
left = 0.5,
right = 1
)
```
Also, we can use `wrap_elements()` to wrap arbitrary graphics in a patchwork-compliant patch, as shown in @fig-we below.
```{r}
#| label: fig-we
#| fig-height: 10
#| fig-cap: "Using inset_element() to add raster images to patchwork plots"
library(magick)
img <- image_read("https://static.vecteezy.com/system/resources/previews/010/795/495/non_2x/diwali-lamp-icon-free-vector.jpg") |>
image_resize("x200")
g1 +
labs(title = "Diwali Sales Data",
subtitle = "Customer numbers (per million population)") +
theme(
plot.title = element_text(hjust = 0.5, size = ts/1.5),
legend.position = "bottom",
legend.key.width = unit(10, "mm"),
legend.key.height = unit(2, "mm")
) +
inset_element(
g3inset,
top = 0.3,
bottom = 0,
left = 0.5,
right = 1
) +
inset_element(
p = ggplot() +
annotation_raster(raster = img, -Inf, Inf, -Inf, Inf) +
theme_void() +
coord_fixed(),
top = 1,
bottom = 0.7,
left = 0.6,
right = 0.9
)
```