Este trabajo se centra en la visualización de las características de valencia y energía de las canciones de un artista, basándose en su nombre. El análisis se realiza en cuatro pasos y utiliza la API de Spotify para obtener los datos necesarios. Al final, se presentan las características de las canciones de cada artista, agrupadas por álbum, lo que permite identificar si existen álbumes que son predominantemente tristes, fuertes/enojados, felices, o chill/relajadas.
# Librerías necesarias
library(httr)
library(ggplot2)
library(plotly)##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:httr':
##
## config
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
Para utilizar la API de Spotify, es necesario registrarse y obtener
las credenciales de la API, que en este trabajo denominamos:
my_client_id<-" "
my_client_secret<-" "
r0 <- POST(
"https://accounts.spotify.com/api/token",
config = authenticate(user = my_client_id,
password = my_client_secret),
body = list(grant_type = "client_credentials"),
encode = "form"
)
token<-content(r0)
bearer_token<-paste(token$token_type, token$access_token)
url_base <-"https://api.spotify.com/v1"artista<-"pomme"
#----------- Paso 1: obtener el id de un artista -------------------------------
get_artist_id <- function(artista, bearer_token){
artista_limpio <- gsub(" ", "_", artista)
query <- paste0(url_base, "/search?q=", artista_limpio, "&type=artist")
response <- GET(query, config = add_headers(Authorization = bearer_token))
resultado <- content(response)
df <- data.frame(id = sapply(resultado[[1]]$items, "[[", "id"),
nombre = sapply(resultado[[1]]$items, "[[", "name"))
print(df)
# Seleccionamos los que nos interesan
id <- df$id[tolower(df$nombre) == tolower(artista)][1]
if(is.null(id) | nrow(df) == 0){
warning("No se han encontrado coincidencias\n")
}
return(id)
}
artista_id <- get_artist_id(artista, bearer_token)## id nombre
## 1 6e3pZKXUxrPfnUPJ960Hd9 Pomme
## 2 3zGV7t4BDmYZBLVA24487b Pommelien Thijs
## 3 3QVolfxko2UyCOtexhVTli Angèle
## 4 7iZ5DNBktesc58hQNjF7Q2 Pommes & Bea
## 5 5j4HeCoUlzhfWtjAfM1acR Stromae
## 6 4wClUlz7cRCjvnPO0ifZmb Nom de Pomme
## 7 1WgXqy2Dd70QQOU7Ay074N AURORA
## 8 37Lr1lIJy824MQIENRUnZn Kurt Masur
## 9 2eRNMtoi82UZUuaL6naDjA Cœur De Pirate
## 10 7KTFZSAt2pE7UwCLseG81I Max Pommer
## 11 3rp4f58JlRHkk8hpdLCer1 Videoclub
## 12 7jo9DLf4vNL9956kMy4tO1 pomme'tto
## 13 7mPT6wrOjVC4visft9qpYQ Hoshi
## 14 2BANCuChR4xcVlWt5Fma6I Nathan Milstein/Leon Pommers
## 15 2Gd7hf7YM1HYmVKRfA9f50 pomme
## 16 2851SiC9O0PIsVKjNMtj4f Les pommes de ma douche
## 17 72QJ6p1y6iz3Gcl2Avc0IU Pomme
## 18 1ePRKRvTUbuZtzZ2wuEzs4 Pomme d'Api
## 19 4hYToXtq7KTJTPnVyi2jZm Pomme
## 20 5yyvYdTeZUvcFIDsUUcljD PommePomme
get_albums<-function(artista_id, bearer_token){
if(!is.null(artista_id)){
url_base<-"https://api.spotify.com/v1"
query<-paste0(url_base,
"/artists/",
artista_id,
"/albums?include_groups=album&limit=50")
respuesta <- GET(query, config = add_headers(Authorization = bearer_token))
resultado<-content(respuesta)
# Obtenemos el data.frame con los nombres y los ids de los albumen del artista:
df <- data.frame(id = sapply(resultado$items, "[[", "id"),
nombre_album = sapply(resultado$items, "[[", "name"))
while (!is.null(resultado$`next`)) {
Sys.sleep(3)
respuesta<-GET(resultado$`next`,
config = add_headers(Authorization = bearer_token))
df<-rbind(df,
data.frame(id = sapply(resultado$items, "[[", "id"),
nombre = sapply(resultado$items, "[[", "name")))
}
return(df)
}
}
df_albums <- get_albums(artista_id, bearer_token);df_albums## id nombre_album
## 1 7liNPWOvTHUYVg5ZhPLBvm (Lot 2) consolation
## 2 6wdpXFepbCvXuDmw45f9FR consolation
## 3 2sCZfWDfMNrIfaew3V3u9a les failles cachées (halloween version)
## 4 2kz6FGzMkZUyGZPywlkcOu les failles cachées
## 5 3Iq43NGfIN8tc8AVJ9Konz les failles
## 6 7BZrBzCAehFjU6mP3JCnmc À peu près (Deluxe)
## 7 65JwIioaq6D5ExpRdtYpCM À peu près
album_id<-df_albums$idget_tracks <- function(album_id, bearer_token){
query <- paste0(url_base, "/albums/", album_id, "/tracks")
# Consulta query y respuesta (response)
respuesta <- GET(query, config = add_headers(Authorization = bearer_token))
resultado <- content(respuesta)
# Obtenemos el data.frame con los nombres y los ids de las canciones del álbum:
df <- data.frame(id = sapply(resultado$items, "[[", "id"),
nombre_canciones = sapply(resultado$items, "[[", "name"),
album_id = album_id)
return(df)
}
lista_albums <- split(df_albums$id, ceiling(seq_along(df_albums$id)/20))
lista_albums<-unlist(lista_albums)
df_tracks <- do.call(rbind,
lapply(lista_albums, get_tracks, bearer_token = bearer_token))
track_id<-df_tracks$idget_track_features <- function(track_id, bearer_token){
query <- paste0(url_base, "/audio-features/", track_id)
respuesta <- GET(query, config = add_headers(Authorization = bearer_token))
resultado <- content(respuesta)
# Obtenemos la energía y la valencia de la canción:
features <- data.frame(id = track_id,
energia = resultado$energy,
valencia = resultado$valence)
return(features)
}
lista_tracks <- df_tracks$id
df_features <- do.call(rbind, lapply(lista_tracks, get_track_features, bearer_token = bearer_token))# Se crea un solo data frame que contenga además la información del nombre y id de los albumes,
# de manera que sea posible agrupar por albumes:
df_final<-merge(df_features, df_tracks, by="id", all=TRUE) # Unimos por id de cancion.
df_final <- merge(df_final, df_albums, by.x = "album_id", by.y = "id", all = TRUE)ggplot(df_final, aes(x = valencia, y = energia, color=factor(nombre_album))) +
geom_point() +
geom_vline(xintercept = 0.5, linetype = "solid", color = "black") +
geom_hline(yintercept = 0.5, linetype = "solid", color = "black") +
scale_x_continuous("Valencia",limits = c(0,1))+
scale_y_continuous("Energía",limits = c(0,1))+
scale_color_discrete(name="Album")+
labs(title = paste("Artista:", artista))+
annotate("text", x = c(0.03, 0.97, 0.05, 1.0),
y = c(0.03, 0.03, 1.0, 1.0),
label = c("Triste", "Chill/relajadas", "Fuertes/enojadas", "Feliz"),
size = 3)+
theme_minimal()# Si se quiere hacer un gráfico interactivo, almacenamos el gráfico anterior en la variable p:
#p<-ggplot(df_final, aes(x = valencia, y = energia, color=factor(nombre_album))) +
# geom_point() +
# geom_vline(xintercept = 0.5, linetype = "solid", color = "black") +
# geom_hline(yintercept = 0.5, linetype = "solid", color = "black") +
# scale_x_continuous("Valencia",limits = c(0,1))+
# scale_y_continuous("Energía",limits = c(0,1))+
# scale_color_discrete(name="Album")+
# labs(title = paste("Artista:", artista))+
# annotate("text", x = c(0.03, 0.97, 0.05, 1.0),
# y = c(0.03, 0.03, 1.0, 1.0),
# label = c("Triste", "Chill/relajadas", "Fuertes/enojadas", "Feliz"),
# size = 3)+
# theme_minimal()
#p_int <- ggplotly(p)
#print(p_int)