-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdashboard.qmd
260 lines (230 loc) · 9.23 KB
/
dashboard.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
---
title: "Today's Top Hits"
format:
dashboard:
logo: "images/logo.png"
orientation: columns
---
## Column {width="35%"}
```{r, loadpackages}
#| echo: false
#| include: false
library(tidyverse)
library(httr2)
library(gt)
```
```{r, createaccesstoken}
#| echo: false
#| include: false
# Define client ID and client secret in order to generate Spotify access token
client_id <- Sys.getenv("SPOTIFY_CLIENT_ID")
client_secret <- Sys.getenv("SPOTIFY_CLIENT_SECRET")
# Generate Spotify access token
req_access_token <- request("https://accounts.spotify.com/api/token") |>
req_method("POST") |>
req_body_raw(paste0(
"grant_type=client_credentials&client_id=",
client_id,
"&client_secret=",
client_secret
), "application/x-www-form-urlencoded") |>
req_perform() |>
resp_body_json()
spotify_access_token <- req_access_token$access_token
```
```{r, gettthplaylist}
#| echo: false
#| include: false
# Get Today's Top Hits Playlist information
tth <- request("https://api.spotify.com/v1/playlists/37i9dQZF1DXcBWIGoYBM5M") |>
req_method("GET") |>
req_headers(
Authorization = paste0("Bearer ", spotify_access_token),
) |>
req_perform() |>
resp_body_json()
# Create data frame with the top hits information
top_hits_df <- data.frame(
song_name = unlist(lapply(tth$tracks$items, FUN = function(x) { x$track$name })),
song_id = unlist(lapply(tth$tracks$items, FUN = function(x) { x$track$id })),
artist_name = unlist(lapply(tth$tracks$items, FUN = function(x) {x$track$album$artists[[1]]$name})),
album_art = unlist(lapply(tth$tracks$items, FUN = function(x) {x$track$album$images[[1]]$url})),
track_duration = unlist(lapply(tth$tracks$items, FUN = function(x) {x$track$duration_ms})),
popularity = unlist(lapply(tth$tracks$items, FUN = function(x) {x$track$popularity}))
)
tempo_list <- vector(mode = "list", length = 50)
for (i in 1:50) {
audio_analysis <- request(paste0("https://api.spotify.com/v1/audio-analysis/", top_hits_df$song_id[i])) |>
req_method("GET") |>
req_headers(
Authorization = paste0("Bearer ", spotify_access_token),
) |>
req_perform() |>
resp_body_json()
# Get tempo for each section of the song
tempo_list[[i]] <- unlist(lapply(audio_analysis$sections, FUN = function(x) {x$tempo }))
}
top_hits_df$tempo <- I(tempo_list)
```
```{r, createtable}
#| expandable: false
generate_svg_circle <- function(popularity_value) {
popularity_value <- as.numeric(popularity_value)
# Calculate the radius of the circle
radius <- 10 + 15 * (popularity_value / 100)
# Interpolate the color from red (popularity = 0) to green (popularity = 100)
circle_colour_picker <- colorRampPalette(c("#B91d1d", "#ED8E11", "#EDDE11", "#1DB954"))
# There are 101 colour values since popularity ranges from 0 to 100
color <- circle_colour_picker(101)[popularity_value + 1]
# Generate the SVG code for the circle
svg_code <- sprintf(
'<svg height="%1$s" width="%1$s"><circle cx="%2$s" cy="%2$s" r="%2$s" stroke="none" stroke-width="0" fill="%3$s" /><text class="circle-text" x="%2$s" y="%2$s" font-size="%4$s" fill="white" text-anchor="middle" dy=".3em">%5$s</text></svg>',
2 * radius, # SVG width and height
radius, # Circle center x, y
color, # Fill color used also for stroke
radius * 0.6, # Font size based on radius
popularity_value # Text to display
)
return(svg_code)
}
# Create the gt table with custom formatting
top_hits_df |>
select(album_art, song_name, artist_name, track_duration, popularity, tempo) |>
gt(id = "custom") |>
cols_label(
album_art = md("**Song**"),
song_name = "",
artist_name = md("**Artist**"),
track_duration = html('<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="15" height="15" viewBox="0,0,255.998,255.998"><g fill="#ffffff" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"><g transform="scale(10.66667,10.66667)"><path d="M12,2c-5.523,0 -10,4.477 -10,10c0,5.523 4.477,10 10,10c5.523,0 10,-4.477 10,-10c0,-5.523 -4.477,-10 -10,-10zM14.586,16l-3.293,-3.293c-0.188,-0.188 -0.293,-0.442 -0.293,-0.707v-5c0,-0.552 0.448,-1 1,-1v0c0.552,0 1,0.448 1,1v4.586l3,3c0.39,0.39 0.39,1.024 0,1.414v0c-0.39,0.39 -1.024,0.39 -1.414,0z"></path></g></g></svg>'),
popularity = md("**Popularity**")
) |>
text_transform(
locations = cells_body(columns = album_art),
fn = function(x) { web_image(url = x, height = 50) }
) |>
text_transform(
fn = function(x) {
generate_svg_circle(x)
},
locations = cells_body(columns = popularity)
) |>
fmt(
columns = track_duration,
fns = function(x) {
num_minutes <- floor(x / 60000)
num_seconds <- ifelse(round((x %% 60000) / 1000) == 60, 59, round((x %% 60000) / 1000))
sprintf("%d:%02d", num_minutes, num_seconds)
}
) |>
cols_nanoplot(
columns = tempo,
plot_type = "line",
new_col_name = "tempos",
new_col_label = md("**Tempo**"),
options = nanoplot_options(
data_point_fill_color = "#1DB954",
data_point_stroke_color = "#1DB954",
data_area_fill_color = "#1DB954",
data_line_stroke_color = "#7D3C98"
)
) |>
cols_align(
align = "center",
columns = popularity
) |>
tab_footnote(
footnote = "The popularity of a track is a value between 0 and 100, with 100 being the most popular. The popularity is calculated by algorithm and is based, in the most part, on the total number of plays the track has had and how recent those plays are.
Generally speaking, songs that are being played a lot now will have a higher popularity than songs that were played a lot in the past.",
locations = cells_column_labels(columns = popularity)
) |>
tab_footnote(
footnote = "The tempo is measured in beats per minute and represents the speed at which the music is played. The visualization shows how the tempo varies across the different sections of the song. Sections with a higher tempo are generally more energetic and upbeat, while sections with a lower tempo may be more emotional or contemplative.",
locations = cells_column_labels(columns = tempos)
) |>
tab_source_note(
source_note = md("**Source:** [Today's Top Hits Playlist](https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M), from the Spotify Web API")
) |>
tab_options(
table.font.color = "#FFFFFF",
table.background.color = "#191414",
table.font.size = px(12),
table.border.top.color = "transparent",
table.border.bottom.color = "transparent",
table_body.hlines.color = "transparent",
table_body.border.bottom.color = "transparent",
column_labels.border.bottom.color = "transparent",
column_labels.border.top.color = "transparent",
footnotes.background.color = "#282828",
source_notes.background.color = "#282828"
) |>
tab_style_body(
style = cell_borders(
sides = c("top", "bottom"),
weight = px(0) # Remove row borders
),
fn = function(x) { is.numeric(x) | is.character(x) }
) |>
opt_css(
css = "
table tr:nth-child(odd) {
background-color: #282828;
}
table tr:hover {
background-color: #383838;
}
.cell-output-display {
overflow-x: unset !important;
}
div#custom {
overflow-x: unset !important;
overflow-y: unset !important;
}
#custom .gt_col_heading {
position: sticky !important;
top: -5px !important;
z-index: 10 !important;
}
"
)
```
## Column {width="65%"}
### Row {height="10%"}
```{r, sendtoojs}
#| echo: false
#| include: false
ojs_define(top_hits_ojs = top_hits_df)
```
```{ojs}
//| expandable: false
// Tranpose the data to make it usable in ojs
top_hits = transpose(top_hits_ojs)
// Create a dropdown menu of the songs
viewof songDropdown = Inputs.select(
top_hits.map(d => d.song_name),
{
label: "Choose a song",
unique: true
}
)
```
### Row {height="70%"}
```{ojs}
//| expandable: false
html`<iframe class="custom-iframe" style="border-radius:12px; display: flex; justify-content: center; align-items: center;"
src=${`https://open.spotify.com/embed/track/${top_hits.find(song => song.song_name === songDropdown).song_id}?utm_source=generator&theme=0`}
width="100%"
height="352"
frameBorder="0"
allowfullscreen=""
allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
loading="lazy">
</iframe>`
```
### Row {height="20%"}
:::{.card expandable="false"}
<div style="background-color: #7D3C98; color: white; border-radius: 10px; padding: 10px; text-align: center; display: flex; align-items: center; justify-content: center; height: 100%;">
<span style="font-size: 1vw; width: 100%;">
**Want to make a project like this?** This dashboard was created by [Melissa Van Bussel](https://www.melissavanbussel.com/) for [Posit's 2024 Table Contest](https://posit.co/blog/announcing-the-2024-table-contest/).<br> You can find a tutorial for this dashboard [here](https://melissavanbussel.github.io/spotify-dashboard) and you can find the code that powers this dashboard [here](https://github.com/melissavanbussel/spotify-dashboard).
</span>
</div>
:::