forked from mccallpitcher/ggiraph-Spring2026
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_inclass_solution.qmd
More file actions
98 lines (75 loc) · 2.66 KB
/
01_inclass_solution.qmd
File metadata and controls
98 lines (75 loc) · 2.66 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
---
title: "Learn R: Interactive plots with ggplot2 and ggiraph"
format: html
editor: visual
editor_options:
chunk_output_type: inline
---
Welcome to your Quarto notebook for today's workshop! Here is the full code for the plots covered in today's workshop.
```{r}
# load packages
library(tidyverse)
library(ggiraph)
library(patchwork)
```
### A. Load data
```{r}
# load data
bowie <- read_csv("data/david_bowie_spotify.csv")
```
### B. Your Turn!
Make the following plot `p1` interactive. Add a tooltip showing `track` and highlight tracks from the same `album` on hover.
**Bonus:** Using `paste0()` and `"<br>"`, replace the tooltip with year, track name, and album name (each on their own line)
```{r}
p1 <- bowie |>
ggplot(aes(x = year, y = popularity)) +
geom_point_interactive(
aes(tooltip = paste(year,"<br>",
"song:",track, "<br>",
"album:", album),
data_id = album),
color = "maroon",
alpha = .7, size = 2) +
theme_minimal()
girafe(ggobj = p1)
```
### C. Another interactive plot
```{r}
# calculate average popularity by album, then plot
p2 <- bowie |>
group_by(album) |>
summarise(avg_popularity = mean(popularity)) |>
ggplot(aes(x = avg_popularity,
y = reorder(album, avg_popularity))) +
geom_col_interactive(aes(data_id = album),
fill = "steelblue") +
labs(y = NULL) +
theme_minimal()
girafe(ggobj = p2)
```
### D. Patch them together
Combine `p2` and `p1` together horizontally into a new plot called `p3`. Then, render the plot using `girafe()`
```{r}
p3 <- p2 + p1 +
plot_layout(widths = c(.8, 2))
girafe(ggobj = p3,
width_svg = 10,
height_svg = 4)
```
### E. Customize
See the `girafe()` code below, that customizes the following elements of the plot:
- `opts_hover()`: the properties of the `data_id` hover. Here I change the fill color to orangered
- `opts_hover_inv()`: the properties of the elements that are *not* highlighted. Here I make them more transparent
- `opts_tooltip()`: the properties of the tooltip. Here I change the background color, font, font color, and margin (padding)
- `opts_zoom()`: Adds the option to zoom in on the plot. You can set a minimum and maximum zoom factor.
```{r}
girafe(ggobj = p3,
width_svg = 10,
height_svg = 4,
options = list(
opts_hover(css = "fill:orangered;"),
opts_hover_inv(css = "opacity:.3;"),
opts_tooltip(css = "background-color:#444;font-family:Arial;color:white;padding:8px;"),
opts_zoom(min = 5, max = 15)
))
```